package cn.stylefeng.guns.modular.rest.transport;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.core.util.MapUtils;
import cn.stylefeng.guns.modular.basic.entity.*;
import cn.stylefeng.guns.modular.basic.model.params.*;
import cn.stylefeng.guns.modular.basic.model.result.*;
import cn.stylefeng.guns.modular.basic.service.*;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStorageOutResult;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageOutService;
import cn.stylefeng.guns.modular.order.entity.OrderTransport;
import cn.stylefeng.guns.modular.order.entity.StorageTaskXlb;
import cn.stylefeng.guns.modular.order.model.params.OrderOutpreparePlatooncarParam;
import cn.stylefeng.guns.modular.order.model.params.OrderTransportDetailedParam;
import cn.stylefeng.guns.modular.order.model.params.OrderTransportParam;
import cn.stylefeng.guns.modular.order.model.result.OrderOutpreparePlatooncarResult;
import cn.stylefeng.guns.modular.order.model.result.OrderTransportDetailedResult;
import cn.stylefeng.guns.modular.order.model.result.OrderTransportResult;
import cn.stylefeng.guns.modular.order.service.OrderOutpreparePlatooncarService;
import cn.stylefeng.guns.modular.order.service.OrderTransportDetailedService;
import cn.stylefeng.guns.modular.order.service.OrderTransportService;
import cn.stylefeng.guns.modular.rest.aop.UserAop;
import cn.stylefeng.guns.modular.rest.transport.vo.GoodQueryVo;
import cn.stylefeng.guns.modular.rest.transport.vo.PrintGoodVo;
import cn.stylefeng.guns.modular.rest.transport.vo.PrintSumVo;
import cn.stylefeng.guns.modular.storage.model.params.StorageOutParam;
import cn.stylefeng.guns.modular.transport.entity.FindPrePickOrder;
import cn.stylefeng.guns.modular.transport.entity.TDispatch;
import cn.stylefeng.guns.modular.transport.entity.TransportCost;
import cn.stylefeng.guns.modular.transport.entity.TransportDispatch;
import cn.stylefeng.guns.modular.transport.model.params.*;
import cn.stylefeng.guns.modular.transport.model.result.*;
import cn.stylefeng.guns.modular.transport.service.*;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.model.result.DictResult;
import cn.stylefeng.guns.sys.modular.system.service.DictService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 运输
 */
@Controller
@RequestMapping("/rest/transport")
public class RestTransportController extends BaseController{

	@Autowired
	private UserAop userAop;

	@Autowired
	private OrderTransportService orderTransportService;


	@Autowired
	private OrderTransportDetailedService orderTransportDetailedService;

	@Autowired
	private BasicPrivatecarService basicPrivatecarService;

	@Autowired
	private TransportDispatchService transportDispatchService;

	@Autowired
	private BasicPutgoodsService basicPutgoodsService;

	private Lock lock = new ReentrantLock();

	@Value("${hxl.api.url}")
	private String hxlApiUrl;

	/**
	 * 查询配送注意事项
	 */
	@ResponseBody
	@RequestMapping("/findCareful")
	public ResponseData findCareful(BasicPutgoodsParam basicPutgoodsParam) {
		BasicPutgoodsResult result = basicPutgoodsService.findCareful(basicPutgoodsParam);
		return ResponseData.success(result);
	}

	@Autowired
	private BasicCustomerService basicCustomerService;

	@Autowired
	private BasicXlbOauth2tokenService basicXlbOauth2tokenService;


	@Autowired
	private DictService dictService;

	/**
	 * APP  查询待配运力客户
	 * @throws ParseException
	 */
	@ResponseBody
	@RequestMapping("/getUnitPage")
	public ResponseData getUnitPage(Long operateIdc,OrderTransportParam orderTransportParam) throws ParseException {
		User user = userAop.getUser();
		if(operateIdc != null) {
			BasicOperate Operate = basicOperateService.getById(operateIdc);
			orderTransportParam.setDeliverId(Operate.getDeliverId());
			orderTransportParam.setDeptId(Operate.getDeptId());
		} else {
			operateIdc = user.getOperateId();
			orderTransportParam.setDeliverId(user.getDeliverId());
			orderTransportParam.setDeptId(user.getDeptId());
		}
		orderTransportParam.setTstate("dispatch");
		if(ToolUtil.isNotEmpty(orderTransportParam.getSetMentiontime())) {//查询前三日甩货
			orderTransportParam.setTimeInterval("'"+DateUtil.getPastDateZd(orderTransportParam.getSetMentiontime(),3)+"' and '"+orderTransportParam.getSetMentiontime()+"'");
		}
		List<OrderTransportResult> list = this.orderTransportService.listgetUnitNewNew(orderTransportParam,operateIdc);
		List<FindPrePickOrder> xlbs = new ArrayList<FindPrePickOrder>();
		List<HxStorageOutResult> hxsl = new ArrayList<HxStorageOutResult>();
		if(operateIdc != null) {
			BasicCustomerParam basicCustomerParam = new BasicCustomerParam();
			basicCustomerParam.setCustomerOperateId(Integer.parseInt(operateIdc.toString()));
			BasicCustomerResult cr = basicCustomerService.findBySpec(basicCustomerParam, null);
			if(cr != null) {
				if(ToolUtil.isNotEmpty(cr.getModeTms())) {
					if(cr.getModeTms().equals("2")) {
						if(ToolUtil.isNotEmpty(cr.getGsnumber())) {
							BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
							oauth2tokenParam.setDeliverId(user.getDeliverId());
							oauth2tokenParam.setGsnumber(cr.getGsnumber());
							BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
							if(oauth2tokenResult != null) {
								if(ToolUtil.isNotEmpty(oauth2tokenResult.getOauth2TokenXlb())) {
									List<String> client_ids = new ArrayList<String>();
									for(OrderTransportResult r : list) {
										if(ToolUtil.isNotEmpty(r.getXlbClientId())) {
											client_ids.add(r.getXlbClientId());
										}
									}
									if(client_ids.size() > 0) {
										//查询新零帮待拣货、待质检单量
//									        String url = "https://test-api.xlbsoft.com/api/hxl.open.wms.findPrePickOrder";
										String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.findPrePickOrder";
										JSONObject json = new JSONObject();
										json.put("client_ids", client_ids);
										String post = HttpRequest.post(url)
												.header("Authorization","bearer "+oauth2tokenResult.getOauth2TokenXlb()).body(json.toString()).execute().body();
//			    							System.out.println("================json："+json+"========================");
//			    							System.out.println("================post："+post+"========================");
										try {
											JSONObject jsonObject = new JSONObject(post);
											if(jsonObject.get("code").toString().equals("0")) {
												JSONArray jsonArray = new JSONArray(jsonObject.get("data").toString());
												for (Object object : jsonArray) {
													JSONObject jsonObject2 = new JSONObject(object.toString());
													FindPrePickOrder findPrePickOrder = new FindPrePickOrder();

													String client_id = jsonObject2.get("client_id").toString();
													if (ToolUtil.isNotEmpty(client_id)&&!client_id.equals("null")) {//门店id
														findPrePickOrder.setClientId(client_id);
													} else {
														continue;
													}

													String pre_pick_order_count = jsonObject2.get("pre_pick_order_count").toString();
													if (ToolUtil.isNotEmpty(pre_pick_order_count)&&!pre_pick_order_count.equals("null")) {//待拣货单量
														findPrePickOrder.setPrePickOrderCount(pre_pick_order_count);
													}

													String pre_check_order_count = jsonObject2.get("pre_check_order_count").toString();
													if (ToolUtil.isNotEmpty(pre_check_order_count)&&!pre_check_order_count.equals("null")) {//待质检数量
														findPrePickOrder.setPreCheckOrderCount(pre_check_order_count);
													}
													xlbs.add(findPrePickOrder);
												}
											}
										} catch (Exception e) {
											e.printStackTrace();
										}
									}
								}
							}
						}
					}
					if(cr.getModeTms().equals("1")||cr.getModeTms().equals("3") || cr.getModeTms().equals("4")) {
						List<Long> getUnit_ids = new ArrayList<Long>();
						for(OrderTransportResult r : list) {
							if(ToolUtil.isNotEmpty(r.getGetUnitId())) {
								getUnit_ids.add(r.getGetUnitId());
							}
						}
						if(getUnit_ids.size() > 0) {
							//查询待拣货、待质检单量
							hxsl = hxStorageOutService.findPrePickOrder(getUnit_ids);
						}
					}
				}
			}
		}
		for (OrderTransportResult r : list) {
			if(ToolUtil.isNotEmpty(r.getXlbClientId())) {
//        		Integer sfsale = orderTransportService.lambdaQuery()
//        				.eq(OrderTransport::getTstate, "待调")
//        				.eq(OrderTransport::getGetUnitId, r.getGetUnitId())
//        				.between(OrderTransport::getSetMentiontime, DateUtil.getPastDateZd(orderTransportParam.getSetMentiontime(),3), DateUtil.getPastDateZd(orderTransportParam.getSetMentiontime(),1))
//        				.count();
//        		r.setSfsale(sfsale+"");
				for (FindPrePickOrder po : xlbs) {
					if(r.getXlbClientId().equals(po.getClientId())) {
						r.setPrePickOrderCount(po.getPrePickOrderCount());
						r.setPreCheckOrderCount(po.getPreCheckOrderCount());
						break;
					}
				}
				for (HxStorageOutResult po : hxsl) {
					if(r.getGetUnitId().equals(po.getGetUnitId())) {
						r.setPrePickOrderCount(po.getPrePickOrderCount());
						r.setPreCheckOrderCount(po.getPreCheckOrderCount());
						break;
					}
				}
			}
			OrderTransportParam orderTransportParam2 = new OrderTransportParam();
			orderTransportParam2.setGetUnitId(r.getGetUnitId());
			orderTransportParam2.setGetLocationId(r.getGetLocationId());
			orderTransportParam2.setTstate("dispatch");
			if(ToolUtil.isNotEmpty(orderTransportParam.getSetMentiontime())) {
				orderTransportParam2.setTimeInterval("'"+DateUtil.getPastDateZd(orderTransportParam.getSetMentiontime(),3)+"' and '"+orderTransportParam.getSetMentiontime()+"'");
			}
			List<OrderTransportResult> list2 = this.orderTransportService.findListBySpecNew(orderTransportParam2,null);
			int orders = 1;
			for (OrderTransportResult r2 : list2) {
				OrderTransportDetailedParam orderTransportDetailedParam = new OrderTransportDetailedParam();
				orderTransportDetailedParam.setTransportNumber(r2.getTransportNumber());
				List<OrderTransportDetailedResult> list3 =  orderTransportDetailedService.findListBySpecWeiPei(orderTransportDetailedParam);
				r2.setOrders(orders+"");
				r2.setList2(list3);
				orders++;
			}
			r.setList(list2);
		}
		return ResponseData.success(list);
	}


	/**
	 * APP  查询待配运力客户
	 * @throws ParseException
	 */
	@ResponseBody
	@RequestMapping("/goodQueryList")
	public ResponseData goodQueryList(String getUnit) {
		User user = userAop.getUser();
		StorageOutParam param = new StorageOutParam();
		if(user.getDeptId() != null){
			param.setDeptId(user.getDeptId());
		}

		if(ToolUtil.isNotEmpty(getUnit)){
			param.setGetUnit(getUnit);
		}

		List<GoodQueryVo> goodQueryVos = this.orderTransportService.goodQueryList(param);
		return ResponseData.success(goodQueryVos);
	}

	/**
	 * APP  查询待配运力客户
	 * @throws ParseException
	 */
	@ResponseBody
	@RequestMapping("/getUnitList")
	public ResponseData getUnitList(Long operateIdc,OrderTransportParam orderTransportParam) throws ParseException {
		User user = userAop.getUser();
		if(operateIdc != null) {
			BasicOperate Operate = basicOperateService.getById(operateIdc);
			orderTransportParam.setDeliverId(Operate.getDeliverId());
			orderTransportParam.setDeptId(Operate.getDeptId());
		} else {
			operateIdc = user.getOperateId();
			orderTransportParam.setDeliverId(user.getDeliverId());
			orderTransportParam.setDeptId(user.getDeptId());
		}
		orderTransportParam.setTstate("dispatch");
		if(ToolUtil.isEmpty(orderTransportParam.getSetMentiontime())){
			orderTransportParam.setSetMentiontime(DateUtil.getDate());
		}
		if(ToolUtil.isNotEmpty(orderTransportParam.getSetMentiontime())) {//查询前三日甩货
			orderTransportParam.setTimeInterval("'"+DateUtil.getPastDateZd(orderTransportParam.getSetMentiontime(),3)+"' and '"+orderTransportParam.getSetMentiontime()+"'");
		}
		//门店
		orderTransportParam.setMendian(user.getAccount());
		List<OrderTransportResult> list = this.orderTransportService.listgetUnitNewNew(orderTransportParam,operateIdc);
		List<FindPrePickOrder> xlbs = new ArrayList<FindPrePickOrder>();
		List<HxStorageOutResult> hxsl = new ArrayList<HxStorageOutResult>();
		if(operateIdc != null) {
			BasicCustomerParam basicCustomerParam = new BasicCustomerParam();
			basicCustomerParam.setCustomerOperateId(Integer.parseInt(operateIdc.toString()));
			BasicCustomerResult cr = basicCustomerService.findBySpec(basicCustomerParam, null);
			if(cr != null) {
				if(ToolUtil.isNotEmpty(cr.getModeTms())) {
					if(cr.getModeTms().equals("2")) {
						if(ToolUtil.isNotEmpty(cr.getGsnumber())) {
							BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
							oauth2tokenParam.setDeliverId(user.getDeliverId());
							oauth2tokenParam.setGsnumber(cr.getGsnumber());
							BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
							if(oauth2tokenResult != null) {
								if(ToolUtil.isNotEmpty(oauth2tokenResult.getOauth2TokenXlb())) {
									List<String> client_ids = new ArrayList<String>();
									for(OrderTransportResult r : list) {
										if(ToolUtil.isNotEmpty(r.getXlbClientId())) {
											client_ids.add(r.getXlbClientId());
										}
									}
									if(client_ids.size() > 0) {
										//查询新零帮待拣货、待质检单量
										String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.findPrePickOrder";
										JSONObject json = new JSONObject();
										json.put("client_ids", client_ids);
										String post = HttpRequest.post(url)
												.header("Authorization","bearer "+oauth2tokenResult.getOauth2TokenXlb()).body(json.toString()).execute().body();
										try {
											JSONObject jsonObject = new JSONObject(post);
											if(jsonObject.get("code").toString().equals("0")) {
												JSONArray jsonArray = new JSONArray(jsonObject.get("data").toString());
												for (Object object : jsonArray) {
													JSONObject jsonObject2 = new JSONObject(object.toString());
													FindPrePickOrder findPrePickOrder = new FindPrePickOrder();
													String client_id = jsonObject2.get("client_id").toString();
													if (ToolUtil.isNotEmpty(client_id)&&!client_id.equals("null")) {//门店id
														findPrePickOrder.setClientId(client_id);
													} else {
														continue;
													}
													String pre_pick_order_count = jsonObject2.get("pre_pick_order_count").toString();
													if (ToolUtil.isNotEmpty(pre_pick_order_count)&&!pre_pick_order_count.equals("null")) {//待拣货单量
														findPrePickOrder.setPrePickOrderCount(pre_pick_order_count);
													}
													String pre_check_order_count = jsonObject2.get("pre_check_order_count").toString();
													if (ToolUtil.isNotEmpty(pre_check_order_count)&&!pre_check_order_count.equals("null")) {//待质检数量
														findPrePickOrder.setPreCheckOrderCount(pre_check_order_count);
													}
													xlbs.add(findPrePickOrder);
												}
											}
										} catch (Exception e) {
											e.printStackTrace();
										}
									}
								}
							}
						}
					}
					if(cr.getModeTms().equals("1")||cr.getModeTms().equals("3") || cr.getModeTms().equals("4")) {
						List<Long> getUnit_ids = new ArrayList<Long>();
						for(OrderTransportResult r : list) {
							if(ToolUtil.isNotEmpty(r.getGetUnitId())) {
								getUnit_ids.add(r.getGetUnitId());
							}
						}
						if(getUnit_ids.size() > 0) {
							//查询待拣货、待质检单量
							hxsl = hxStorageOutService.findPrePickOrder(getUnit_ids);
						}
					}
				}
			}
		}
		for (OrderTransportResult r : list) {
			if(ToolUtil.isNotEmpty(r.getXlbClientId())) {
				for (FindPrePickOrder po : xlbs) {
					if(r.getXlbClientId().equals(po.getClientId())) {
						r.setPrePickOrderCount(po.getPrePickOrderCount());
						r.setPreCheckOrderCount(po.getPreCheckOrderCount());
						break;
					}
				}
				for (HxStorageOutResult po : hxsl) {
					if(r.getGetUnitId().equals(po.getGetUnitId())) {
						r.setPrePickOrderCount(po.getPrePickOrderCount());
						r.setPreCheckOrderCount(po.getPreCheckOrderCount());
						break;
					}
				}
			}
		}
		return ResponseData.success(list);
	}

	@ResponseBody
	@RequestMapping("/getUnitMxList")
	public ResponseData getUnitMxList(OrderTransportParam orderTransportParam) throws ParseException {
		orderTransportParam.setTstate("dispatch");
		if(ToolUtil.isEmpty(orderTransportParam.getSetMentiontime())){
			orderTransportParam.setSetMentiontime(DateUtil.getDate());
		}
		if(ToolUtil.isNotEmpty(orderTransportParam.getSetMentiontime())) {
			orderTransportParam.setTimeInterval("'"+DateUtil.getPastDateZd(orderTransportParam.getSetMentiontime(),3)+"' and '"+orderTransportParam.getSetMentiontime()+"'");
		}
		List<OrderTransportResult> list2 = this.orderTransportService.findListBySpecNew(orderTransportParam,null);
		int orders = 1;
		for (OrderTransportResult r2 : list2) {
			OrderTransportDetailedParam orderTransportDetailedParam = new OrderTransportDetailedParam();
			orderTransportDetailedParam.setTransportNumber(r2.getTransportNumber());
			List<OrderTransportDetailedResult> list3 =  orderTransportDetailedService.findListBySpecWeiPei(orderTransportDetailedParam);
			r2.setOrders(orders+"");
			r2.setList2(list3);
			orders++;
		}
		return ResponseData.success(list2);
	}


    @Autowired
    private HxStorageOutService hxStorageOutService;

	/**
	 * APP(页面三)查询空闲车辆
	 */
	@ResponseBody
	@RequestMapping("/privatecarlist")
	public ResponseData privatecarlist(BasicPrivatecarParam basicPrivatecarParam) {
		User user = userAop.getUser();
		basicPrivatecarParam.setDeliverId(user.getDeliverId());
		Long deptId = user.getDeptId();
		return ResponseData.success(this.basicPrivatecarService.findListBySpec(basicPrivatecarParam,deptId,user.getOperateId()));
	}

	/**
	 * APP(页面三)查询空闲车辆
	 */
	@ResponseBody
	@RequestMapping("/privatecarlist8")
	public ResponseData privatecarlist8(BasicPrivatecarParam basicPrivatecarParam) {
		User user = userAop.getUser();
		basicPrivatecarParam.setDeliverId(user.getDeliverId());
		return ResponseData.success(this.basicPrivatecarService.findListBySpec8(basicPrivatecarParam,null,user.getOperateId()));
	}

	/**
	 * APP(页面三)查询空闲车辆
	 */
	@ResponseBody
	@RequestMapping("/privatecarPagelist")
	public LayuiPageInfo privatecarPagelist(BasicPrivatecarParam basicPrivatecarParam) {
		User user = userAop.getUser();
		basicPrivatecarParam.setDeliverId(user.getDeliverId());
		return this.basicPrivatecarService.appFindPageBySpec(basicPrivatecarParam,null,user.getOperateId());
	}

	/**
	 * APP车辆选择
	 * 查询已配置车辆
	 */
	@ResponseBody
	@RequestMapping("/findCarListBySpecToo")
	public ResponseData findCarListBySpecToo(TransportDispatchParam transportDispatchParam,String tstate,String getUnit, String getLocation) {
		User user = userAop.getUser();
		transportDispatchParam.setDeliverId(user.getDeliverId());
		transportDispatchParam.setDeptId(user.getDeptId());
		String token = "Wait";
		String dispatch = "";
		if (ToolUtil.isNotEmpty(tstate)) {
			token = "";
			dispatch = "daidingjia";
		}
		List<TransportDispatchResult> list = this.transportDispatchService.findCarListBySpecToo(transportDispatchParam,getUnit,getLocation,token,null,dispatch,user.getOperateId());
		for (TransportDispatchResult r : list) {
			OrderTransportParam orderTransportParam = new OrderTransportParam();
			orderTransportParam.setDeptId(user.getDeptId());
			orderTransportParam.setTstate("dispatch");
			orderTransportParam.setOrderNumber(r.getDispatchNumber());
			if (ToolUtil.isNotEmpty(tstate)) {
				orderTransportParam.setTstate("too");
			}
			List<OrderTransportResult> list2 = this.orderTransportService.carDetailsSingleToo(orderTransportParam,r.getCarId(),dispatch,user.getOperateId());
			List<FindPrePickOrder> xlbs = new ArrayList<FindPrePickOrder>();
			List<HxStorageOutResult> hxsl = new ArrayList<HxStorageOutResult>();
			if(user.getOperateId() != null) {
				BasicCustomerParam basicCustomerParam = new BasicCustomerParam();
				basicCustomerParam.setCustomerOperateId(Integer.parseInt(user.getOperateId().toString()));
				BasicCustomerResult cr = basicCustomerService.findBySpec(basicCustomerParam, null);
				if(cr != null) {
					if(ToolUtil.isNotEmpty(cr.getModeTms())&&cr.getModeTms().equals("2")) {
						if(ToolUtil.isNotEmpty(cr.getGsnumber())) {
							BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
							oauth2tokenParam.setDeliverId(user.getDeliverId());
							oauth2tokenParam.setGsnumber(cr.getGsnumber());
							BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
							if(oauth2tokenResult != null) {
								if(ToolUtil.isNotEmpty(oauth2tokenResult.getOauth2TokenXlb())) {
									List<String> client_ids = new ArrayList<String>();
									for(OrderTransportResult xlbr : list2) {
										if(ToolUtil.isNotEmpty(xlbr.getXlbClientId())) {
											client_ids.add(xlbr.getXlbClientId());
										}
									}
									if(client_ids.size() > 0) {
										//查询新零帮待拣货、待质检单量
//							            String url = "https://test-api.xlbsoft.com/api/hxl.open.wms.findPrePickOrder";
										String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.findPrePickOrder";
										JSONObject json = new JSONObject();
										json.put("client_ids", client_ids);
										String post = HttpRequest.post(url)
												.header("Authorization","bearer "+oauth2tokenResult.getOauth2TokenXlb()).body(json.toString()).execute().body();
//	        							System.out.println("================json："+json+"========================");
//	        							System.out.println("================post："+post+"========================");
										try {
											JSONObject jsonObject = new JSONObject(post);
											if(jsonObject.get("code").toString().equals("0")) {
												JSONArray jsonArray = new JSONArray(jsonObject.get("data").toString());
												for (Object object : jsonArray) {
													JSONObject jsonObject2 = new JSONObject(object.toString());
													FindPrePickOrder findPrePickOrder = new FindPrePickOrder();

													String client_id = jsonObject2.get("client_id").toString();
													if (ToolUtil.isNotEmpty(client_id)&&!client_id.equals("null")) {//门店id
														findPrePickOrder.setClientId(client_id);
													} else {
														continue;
													}

													String pre_pick_order_count = jsonObject2.get("pre_pick_order_count").toString();
													if (ToolUtil.isNotEmpty(pre_pick_order_count)&&!pre_pick_order_count.equals("null")) {//待拣货单量
														findPrePickOrder.setPrePickOrderCount(pre_pick_order_count);
													}

													String pre_check_order_count = jsonObject2.get("pre_check_order_count").toString();
													if (ToolUtil.isNotEmpty(pre_check_order_count)&&!pre_check_order_count.equals("null")) {//待质检数量
														findPrePickOrder.setPreCheckOrderCount(pre_check_order_count);
													}
													xlbs.add(findPrePickOrder);
												}
											}
										} catch (Exception e) {
											e.printStackTrace();
										}
									}
								}
							}
						}
					}
					if(cr.getModeTms().equals("1")||cr.getModeTms().equals("3") || cr.getModeTms().equals("4")) {
						List<Long> getUnit_ids = new ArrayList<Long>();
						for(OrderTransportResult r2 : list2) {
							if(ToolUtil.isNotEmpty(r2.getGetUnitId())) {
								getUnit_ids.add(r2.getGetUnitId());
							}
						}
						if(getUnit_ids.size() > 0) {
							//查询待拣货、待质检单量
							hxsl = hxStorageOutService.findPrePickOrder(getUnit_ids);
						}
					}
				}
			}
			for (OrderTransportResult r2 : list2) {
				if(ToolUtil.isNotEmpty(r2.getXlbClientId())) {
					Integer sfsale = orderTransportService.lambdaQuery()
							.eq(OrderTransport::getTstate, "待调")
							.eq(OrderTransport::getGetUnitId, r2.getGetUnitId())
							.between(OrderTransport::getSetMentiontime, DateUtil.getPastDate(3), DateUtil.getPastDate(1))
							.count();
					r2.setSfsale(sfsale+"");
					for (FindPrePickOrder po : xlbs) {
						if(r2.getXlbClientId().equals(po.getClientId())) {
							r2.setPrePickOrderCount(po.getPrePickOrderCount());
							r2.setPreCheckOrderCount(po.getPreCheckOrderCount());
							break;
						}
					}
					for (HxStorageOutResult po : hxsl) {
						if(r2.getGetUnitId().equals(po.getGetUnitId())) {
							r2.setPrePickOrderCount(po.getPrePickOrderCount());
							r2.setPreCheckOrderCount(po.getPreCheckOrderCount());
							break;
						}
					}
				}
			}
			r.setList(list2);
		}
		return ResponseData.success(list);
	}

	/**
	 * 司机装车
	 * APP车辆选择
	 * 查询已配置车辆
	 */
	@ResponseBody
	@RequestMapping("/findCarListBySpecToo_driver")
	public ResponseData findCarListBySpecToo_driver(TransportDispatchParam transportDispatchParam,String tstate,String getUnit, String getLocation) {
		User user = userAop.getUser();
		String token = "Wait";
		String dispatch = "";
		if (ToolUtil.isNotEmpty(tstate)) {
			token = "";
			dispatch = "daidingjia";
		}
		BasicDriverParam basicDriverParam = new BasicDriverParam();
		basicDriverParam.setUserId(user.getUserId());
		BasicDriverResult basicDriverResult = basicDriverService.findBySpec(basicDriverParam,null);
		BasicPrivatecarResult basicPrivatecarResult = new BasicPrivatecarResult();
		if(basicDriverResult != null) {
			BasicPrivatecarParam BasicPrivatecarParam = new BasicPrivatecarParam();
			BasicPrivatecarParam.setDriverId1(Long.parseLong(basicDriverResult.getId().toString()));
			basicPrivatecarResult = basicPrivatecarService.findBySpec(BasicPrivatecarParam, null,null);
		} else {
			return ResponseData.success();
		}
		if(basicPrivatecarResult == null || ToolUtil.isEmpty(basicPrivatecarResult.getPrivatecarCarnumber())) {
			return ResponseData.success();
		}
		transportDispatchParam.setDeliverId(user.getDeliverId());
		transportDispatchParam.setCarId(Long.parseLong(basicPrivatecarResult.getId().toString()));
		List<TransportDispatchResult> list = this.transportDispatchService.findCarListBySpecToo(transportDispatchParam,getUnit,getLocation,token,null,dispatch,null);
		for (TransportDispatchResult r : list) {
			OrderTransportParam orderTransportParam = new OrderTransportParam();
			orderTransportParam.setTstate("dispatch");
			orderTransportParam.setOrderNumber(r.getDispatchNumber());
			if (ToolUtil.isNotEmpty(tstate)) {
				orderTransportParam.setTstate("too");
			}
			List<OrderTransportResult> list2 = this.orderTransportService.carDetailsSingleToo(orderTransportParam,r.getCarId(),dispatch,null);
			List<FindPrePickOrder> xlbs = new ArrayList<FindPrePickOrder>();
			List<HxStorageOutResult> hxsl = new ArrayList<HxStorageOutResult>();
			if(user.getOperateId() != null) {
				BasicCustomerParam basicCustomerParam = new BasicCustomerParam();
				basicCustomerParam.setCustomerOperateId(Integer.parseInt(user.getOperateId().toString()));
				BasicCustomerResult cr = basicCustomerService.findBySpec(basicCustomerParam, null);
				if(cr != null) {
					if(ToolUtil.isNotEmpty(cr.getModeTms())&&cr.getModeTms().equals("2")) {
						if(ToolUtil.isNotEmpty(cr.getGsnumber())) {
							BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
							oauth2tokenParam.setDeliverId(user.getDeliverId());
							oauth2tokenParam.setGsnumber(cr.getGsnumber());
							BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
							if(oauth2tokenResult != null) {
								if(ToolUtil.isNotEmpty(oauth2tokenResult.getOauth2TokenXlb())) {
									List<String> client_ids = new ArrayList<String>();
									for(OrderTransportResult xlbr : list2) {
										if(ToolUtil.isNotEmpty(xlbr.getXlbClientId())) {
											client_ids.add(xlbr.getXlbClientId());
										}
									}
									if(client_ids.size() > 0) {
										//查询新零帮待拣货、待质检单量
//							            String url = "https://test-api.xlbsoft.com/api/hxl.open.wms.findPrePickOrder";
										String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.findPrePickOrder";
										JSONObject json = new JSONObject();
										json.put("client_ids", client_ids);
										String post = HttpRequest.post(url)
												.header("Authorization","bearer "+oauth2tokenResult.getOauth2TokenXlb()).body(json.toString()).execute().body();
//	        							System.out.println("================json："+json+"========================");
//	        							System.out.println("================post："+post+"========================");
										try {
											JSONObject jsonObject = new JSONObject(post);
											if(jsonObject.get("code").toString().equals("0")) {
												JSONArray jsonArray = new JSONArray(jsonObject.get("data").toString());
												for (Object object : jsonArray) {
													JSONObject jsonObject2 = new JSONObject(object.toString());
													FindPrePickOrder findPrePickOrder = new FindPrePickOrder();

													String client_id = jsonObject2.get("client_id").toString();
													if (ToolUtil.isNotEmpty(client_id)&&!client_id.equals("null")) {//门店id
														findPrePickOrder.setClientId(client_id);
													} else {
														continue;
													}

													String pre_pick_order_count = jsonObject2.get("pre_pick_order_count").toString();
													if (ToolUtil.isNotEmpty(pre_pick_order_count)&&!pre_pick_order_count.equals("null")) {//待拣货单量
														findPrePickOrder.setPrePickOrderCount(pre_pick_order_count);
													}

													String pre_check_order_count = jsonObject2.get("pre_check_order_count").toString();
													if (ToolUtil.isNotEmpty(pre_check_order_count)&&!pre_check_order_count.equals("null")) {//待质检数量
														findPrePickOrder.setPreCheckOrderCount(pre_check_order_count);
													}
													xlbs.add(findPrePickOrder);
												}
											}
										} catch (Exception e) {
											e.printStackTrace();
										}
									}
								}
							}
						}
					}
					if(cr.getModeTms().equals("1")||cr.getModeTms().equals("3") || cr.getModeTms().equals("4")) {
						List<Long> getUnit_ids = new ArrayList<Long>();
						for(OrderTransportResult r2 : list2) {
							if(ToolUtil.isNotEmpty(r2.getGetUnitId())) {
								getUnit_ids.add(r2.getGetUnitId());
							}
						}
						if(getUnit_ids.size() > 0) {
							//查询待拣货、待质检单量
							hxsl = hxStorageOutService.findPrePickOrder(getUnit_ids);
						}
					}
				}
			}
			for (OrderTransportResult r2 : list2) {
				if(ToolUtil.isNotEmpty(r2.getXlbClientId())) {
					Integer sfsale = orderTransportService.lambdaQuery()
							.eq(OrderTransport::getTstate, "待调")
							.eq(OrderTransport::getGetUnitId, r2.getGetUnitId())
							.between(OrderTransport::getSetMentiontime, DateUtil.getPastDate(3), DateUtil.getPastDate(1))
							.count();
					r2.setSfsale(sfsale+"");
					for (FindPrePickOrder po : xlbs) {
						if(r2.getXlbClientId().equals(po.getClientId())) {
							r2.setPrePickOrderCount(po.getPrePickOrderCount());
							r2.setPreCheckOrderCount(po.getPreCheckOrderCount());
							break;
						}
					}
					for (HxStorageOutResult po : hxsl) {
						if(r2.getGetUnitId().equals(po.getGetUnitId())) {
							r2.setPrePickOrderCount(po.getPrePickOrderCount());
							r2.setPreCheckOrderCount(po.getPreCheckOrderCount());
							break;
						}
					}
				}
			}
			r.setList(list2);
		}
		return ResponseData.success(list);
	}

	/**
	 * APP追加明细
	 * 查询已完成配置车辆
	 */
	@ResponseBody
	@RequestMapping("/findCarListBySpecTooZhuijia4")
	public ResponseData findCarListBySpecTooZhuijia4(TransportDispatchParam transportDispatchParam,String tstate,String getUnit, String getLocation) {
		User user = userAop.getUser();
		transportDispatchParam.setDeliverId(user.getDeliverId());
		transportDispatchParam.setDeptId(user.getDeptId());
		String token = "";
		String dispatch = "zhuijia";
		List<TransportDispatchResult> list = this.transportDispatchService.findCarListBySpecToo4(transportDispatchParam,getUnit,getLocation,token,null,dispatch,user.getOperateId());
		for (TransportDispatchResult r : list) {
			OrderTransportParam orderTransportParam = new OrderTransportParam();
			orderTransportParam.setDeptId(user.getDeptId());
			orderTransportParam.setTstate("too");
			orderTransportParam.setOrderNumber(r.getDispatchNumber());
			List<OrderTransportResult> list2 = this.orderTransportService.carDetailsSingleToo(orderTransportParam,r.getCarId(),dispatch,user.getOperateId());
			r.setList(list2);
		}
		return ResponseData.success(list);
	}

	/**
	 * APP追加明细
	 * 查询已完成配置车辆
	 */
	@ResponseBody
	@RequestMapping("/findCarListBySpecTooZhuijia")
	public ResponseData findCarListBySpecTooZhuijia(TransportDispatchParam transportDispatchParam,String tstate,String getUnit, String getLocation) {
		User user = userAop.getUser();
		transportDispatchParam.setDeliverId(user.getDeliverId());
		transportDispatchParam.setDeptId(user.getDeptId());
		String token = "";
		String dispatch = "zhuijia";
		List<TransportDispatchResult> list = this.transportDispatchService.findCarListBySpecToo(transportDispatchParam,getUnit,getLocation,token,null,dispatch,user.getOperateId());
		for (TransportDispatchResult r : list) {
			OrderTransportParam orderTransportParam = new OrderTransportParam();
			orderTransportParam.setDeptId(user.getDeptId());
			orderTransportParam.setTstate("too");
			orderTransportParam.setOrderNumber(r.getDispatchNumber());
			List<OrderTransportResult> list2 = this.orderTransportService.carDetailsSingleToo(orderTransportParam,r.getCarId(),dispatch,user.getOperateId());
			r.setList(list2);
		}
		return ResponseData.success(list);
	}


	@ResponseBody
	@RequestMapping("/loadingTime")
	public ResponseData loadingTime(Integer id) {
//		User user = userAop.getUser();
		TransportMsgParam msg = new TransportMsgParam();
		msg.setId(id);
		msg.setLondingTime(DateUtil.getDateS());
		transportMsgService.update(msg);
		return ResponseData.success();
	}

	/**
	 * APP追加明细
	 * 查询已完成配置车辆
	 */
	@ResponseBody
	@RequestMapping("/findCarListBySpecTooZhuijia_driver4")
	public ResponseData findCarListBySpecTooZhuijia_driver(TransportDispatchParam transportDispatchParam,String tstate,String getUnit, String getLocation,Long operateId) {
		User user = userAop.getUser();
		BasicDriverParam basicDriverParam = new BasicDriverParam();
		basicDriverParam.setUserId(user.getUserId());
		BasicDriverResult basicDriverResult = basicDriverService.findBySpec(basicDriverParam,null);
		BasicPrivatecarResult basicPrivatecarResult = new BasicPrivatecarResult();
		if(basicDriverResult != null) {
			BasicPrivatecarParam BasicPrivatecarParam = new BasicPrivatecarParam();
			BasicPrivatecarParam.setDriverId1(Long.parseLong(basicDriverResult.getId().toString()));
			basicPrivatecarResult = basicPrivatecarService.findBySpec(BasicPrivatecarParam, null,null);
		} else {
			return ResponseData.success();
		}
		if(basicPrivatecarResult == null) {
			return ResponseData.success();
		}
		transportDispatchParam.setDeliverId(user.getDeliverId());
		transportDispatchParam.setCarId(Long.parseLong(basicPrivatecarResult.getId().toString()));
		transportDispatchParam.setOperateId(operateId);
		String token = "";
		String dispatch = "zhuijia";
		List<TransportDispatchResult> list = this.transportDispatchService.findCarListBySpecToo4(transportDispatchParam,getUnit,getLocation,token,null,dispatch,null);
		for (TransportDispatchResult r : list) {
			OrderTransportParam orderTransportParam = new OrderTransportParam();
			orderTransportParam.setTstate("too");
			orderTransportParam.setOrderNumber(r.getDispatchNumber());
			List<OrderTransportResult> list2 = this.orderTransportService.carDetailsSingleToo(orderTransportParam,r.getCarId(),dispatch,null);
			r.setList(list2);
		}
		return ResponseData.success(list);
	}

	/**
	 * APP(车辆选择) 确定
	 */
	@RequestMapping("/batchassign")
	@ResponseBody
	public ResponseData batchassign(Long[] gids,String[] nums,String[] orders,String[] arrorders,Long carId) {
		List<OrderTransportDetailedParam> _list2 = new ArrayList<OrderTransportDetailedParam>();
		for (int i = 0; i < orders.length; i++) {
			OrderTransportDetailedParam o = new OrderTransportDetailedParam();
			try {
				o.setTransportNumber(orders[i]);
				o.setNum(nums[i]);
				o.setGoodId(gids[i]);
				_list2.add(o);
			} catch (Exception e) {
				return ResponseData.error("数据错误");
			}
		}
		for (int i = 0; i < arrorders.length; i++) {
			OrderTransportDetailedParam o = new OrderTransportDetailedParam();
			try {
				o.setTransportNumber(arrorders[i]);
				_list2.add(o);
			} catch (Exception e) {
				return ResponseData.error("数据错误");
			}
		}
		ResponseData data = new ResponseData();
		User user = userAop.getUser();

		lock.lock();//获取锁
		try {
			data = transportDispatchService.batchassign_app(_list2,carId,user);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
		return data;
	}

	/**
	 * 司机
	 * APP装车 确定
	 */
	@RequestMapping("/batchassign_driver")
	@ResponseBody
	public ResponseData batchassign_driver(Long operateId,Long[] gids,String[] nums,String[] orders,String[] arrorders
			,String loadingType,String[] loadingNumbers,String scanDress) {
		List<OrderTransportDetailedParam> _list2 = new ArrayList<OrderTransportDetailedParam>();
		for (int i = 0; i < orders.length; i++) {
			OrderTransportDetailedParam o = new OrderTransportDetailedParam();
			try {
				o.setTransportNumber(orders[i]);
				o.setNum(nums[i]);
				o.setGoodId(gids[i]);
				_list2.add(o);
			} catch (Exception e) {
				return ResponseData.error("数据错误");
			}
		}
		for (int i = 0; i < arrorders.length; i++) {
			OrderTransportDetailedParam o = new OrderTransportDetailedParam();
			try {
				o.setTransportNumber(arrorders[i]);
				_list2.add(o);
			} catch (Exception e) {
				return ResponseData.error("数据错误");
			}
		}
		ResponseData data = new ResponseData();
		User user = userAop.getUser();

		lock.lock();//获取锁
		try {
			BasicDriverParam basicDriverParam = new BasicDriverParam();
			basicDriverParam.setUserId(user.getUserId());
			BasicDriverResult basicDriverResult = basicDriverService.findBySpec(basicDriverParam,null);
			BasicPrivatecarResult basicPrivatecarResult = new BasicPrivatecarResult();
			if(basicDriverResult != null) {
				BasicPrivatecarParam BasicPrivatecarParam = new BasicPrivatecarParam();
				BasicPrivatecarParam.setDriverId1(Long.parseLong(basicDriverResult.getId().toString()));
				basicPrivatecarResult = basicPrivatecarService.findBySpec(BasicPrivatecarParam, null,null);
			} else {
				return ResponseData.error("未查询到您的信息");
			}
			if(basicPrivatecarResult == null || ToolUtil.isEmpty(basicPrivatecarResult.getPrivatecarCarnumber())) {
				return ResponseData.error("未查询到您关联的车辆信息");
			}
			BasicOperate basicOperate = basicOperateService.getById(operateId);
			TransportMsgParam dcqd = new TransportMsgParam();
			dcqd.setV3(basicPrivatecarResult.getId()+"");
			dcqd.setDeptId(basicOperate.getDeptId());
			dcqd.setStatus("到仓签到");
			TransportMsgResult msgResult = transportMsgService.findDcqdBySpec(dcqd,operateId);
			if(msgResult == null) {
				data.setSuccess(true);
				data.setMessage("检测到还未签到！请先进行签到");
			} else {
				try {
					BigDecimal fu24 = new BigDecimal("-24");
					BigDecimal xiangcha = new BigDecimal(DateUtil.getDatePoorMin(msgResult.getTimes(), DateUtil.getDateS()));//计算签到时间是否超过24小时
					if(xiangcha.compareTo(fu24) != -1) {
						//天津好速来项目
						if(msgResult !=null && ToolUtil.isEmpty(msgResult.getLondingTime()) && 44 == operateId){
							data.setSuccess(true);
							data.setMessage("检测到还未开始装车！请先进行【开始装车】");
						}else{
							data = transportDispatchService.batchassign_driver(_list2,Long.parseLong(basicPrivatecarResult.getId().toString()),loadingType,loadingNumbers,user,basicOperate,scanDress);
						}
					} else {
						data.setSuccess(true);
						data.setMessage("检测到还未签到！请先进行签到");
					}
				} catch (Exception e) {
					e.printStackTrace();
					data = transportDispatchService.batchassign_driver(_list2,Long.parseLong(basicPrivatecarResult.getId().toString()),loadingType,loadingNumbers,user,basicOperate,scanDress);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
		return data;
	}

	/**
	 * 司机
	 * APP装车 确定
	 */
	@RequestMapping("/getQx")
	@ResponseBody
	public ResponseData getQx() {
		User user = userAop.getUser();
		Long operateId = user.getOperateId();
		BasicDriverParam basicDriverParam = new BasicDriverParam();
		basicDriverParam.setUserId(user.getUserId());
		BasicDriverResult basicDriverResult = basicDriverService.findBySpec(basicDriverParam,null);
		BasicPrivatecarResult basicPrivatecarResult = new BasicPrivatecarResult();
		if(basicDriverResult != null) {
			if(ToolUtil.isNotEmpty(basicDriverResult.getDriverOperateId())){
				operateId =basicDriverResult.getDriverOperateId().longValue();
			}
			BasicPrivatecarParam BasicPrivatecarParam = new BasicPrivatecarParam();
			BasicPrivatecarParam.setDriverId1(Long.parseLong(basicDriverResult.getId().toString()));
			basicPrivatecarResult = basicPrivatecarService.findBySpec(BasicPrivatecarParam, null,null);
		} else {
			return ResponseData.error("未查询到您的信息");
		}
		if(basicPrivatecarResult == null || ToolUtil.isEmpty(basicPrivatecarResult.getPrivatecarCarnumber())) {
			return ResponseData.error("未查询到您关联的车辆信息");
		}
		BasicOperate basicOperate = basicOperateService.getById(operateId);
		TransportMsgParam dcqd = new TransportMsgParam();
		dcqd.setV3(basicPrivatecarResult.getId()+"");
		dcqd.setDeptId(basicOperate.getDeptId());
		dcqd.setStatus("到仓签到");
		TransportMsgResult msgResult = transportMsgService.findDcqdBySpec(dcqd,operateId);
		if(msgResult == null) {
			return ResponseData.error("检测到还未签到！请先进行签到");
		} else {
			try {
				BigDecimal fu24 = new BigDecimal("-24");
				BigDecimal xiangcha = new BigDecimal(DateUtil.getDatePoorMin(msgResult.getTimes(), DateUtil.getDateS()));//计算签到时间是否超过24小时
				if(xiangcha.compareTo(fu24) != -1) {
					//天津好速来项目
					if(msgResult !=null && ToolUtil.isEmpty(msgResult.getLondingTime()) && 44 == operateId){
//						return ResponseData.error("检测到还未开始装车！请先进行【开始装车】");
					}
				} else {
					return ResponseData.error("检测到还未签到！请先进行签到");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return ResponseData.success();
	}

	/**
	 * 司机
	 * APP装车 确定
	 */
	@RequestMapping("/getQx1")
	@ResponseBody
	public ResponseData getQx1() {
		User user = userAop.getUser();
		Long operateId = user.getOperateId();
		BasicDriverParam basicDriverParam = new BasicDriverParam();
		basicDriverParam.setUserId(user.getUserId());
		BasicDriverResult basicDriverResult = basicDriverService.findBySpec(basicDriverParam,null);
		BasicPrivatecarResult basicPrivatecarResult = new BasicPrivatecarResult();
		if(basicDriverResult != null) {
			if(ToolUtil.isNotEmpty(basicDriverResult.getDriverOperateId())){
				operateId =basicDriverResult.getDriverOperateId().longValue();
			}
			BasicPrivatecarParam BasicPrivatecarParam = new BasicPrivatecarParam();
			BasicPrivatecarParam.setDriverId1(Long.parseLong(basicDriverResult.getId().toString()));
			basicPrivatecarResult = basicPrivatecarService.findBySpec(BasicPrivatecarParam, null,null);
		} else {
			return ResponseData.error("未查询到您的信息");
		}
		if(basicPrivatecarResult == null || ToolUtil.isEmpty(basicPrivatecarResult.getPrivatecarCarnumber())) {
			return ResponseData.error("未查询到您关联的车辆信息");
		}
		BasicOperate basicOperate = basicOperateService.getById(operateId);
		TransportMsgParam dcqd = new TransportMsgParam();
		dcqd.setV3(basicPrivatecarResult.getId()+"");
		dcqd.setDeptId(basicOperate.getDeptId());
		dcqd.setStatus("到仓签到");
		TransportMsgResult msgResult = transportMsgService.findDcqdBySpec(dcqd,operateId);
		if(msgResult == null) {
			return ResponseData.error("检测到还未签到！请先进行签到");
		} else {
			try {
				BigDecimal fu24 = new BigDecimal("-24");
				BigDecimal xiangcha = new BigDecimal(DateUtil.getDatePoorMin(msgResult.getTimes(), DateUtil.getDateS()));//计算签到时间是否超过24小时
				if(xiangcha.compareTo(fu24) != -1) {
				} else {
					return ResponseData.error("检测到还未签到！请先进行签到");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return ResponseData.success();
	}

	/**
	 * APP(追加明细) 确定
	 */
	@RequestMapping("/batchassignDispatchNumber")
	@ResponseBody
	public ResponseData batchassignDispatchNumber(Long[] gids,String[] nums,String[] orders,String[] arrorders,String dispatchNumber) {
		List<OrderTransportDetailedParam> _list2 = new ArrayList<OrderTransportDetailedParam>();
		for (int i = 0; i < orders.length; i++) {
			OrderTransportDetailedParam o = new OrderTransportDetailedParam();
			try {
				o.setTransportNumber(orders[i]);
				o.setNum(nums[i]);
				o.setGoodId(gids[i]);
				_list2.add(o);
			} catch (Exception e) {
				return ResponseData.error("数据错误");
			}
		}
		for (int i = 0; i < arrorders.length; i++) {
			OrderTransportDetailedParam o = new OrderTransportDetailedParam();
			try {
				o.setTransportNumber(arrorders[i]);
				_list2.add(o);
			} catch (Exception e) {
				return ResponseData.error("数据错误");
			}
		}
		ResponseData data = new ResponseData();
		User user = userAop.getUser();
		lock.lock();//获取锁
		try {
			data = transportDispatchService.batchassignNewDispatchNumber(_list2,dispatchNumber,data,user);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
		return data;
	}

	/**
	 * 司机
	 * APP(追加明细) 确定
	 */
	@RequestMapping("/batchassignDispatchNumber_driver")
	@ResponseBody
	public ResponseData batchassignDispatchNumber_driver(Long[] gids,String[] nums,String[] orders,String[] arrorders
			,String dispatchNumber,Long operateId,String scanDress) {
		List<OrderTransportDetailedParam> _list2 = new ArrayList<OrderTransportDetailedParam>();
		for (int i = 0; i < orders.length; i++) {
			OrderTransportDetailedParam o = new OrderTransportDetailedParam();
			try {
				o.setTransportNumber(orders[i]);
				o.setNum(nums[i]);
				o.setGoodId(gids[i]);
				_list2.add(o);
			} catch (Exception e) {
				return ResponseData.error("数据错误");
			}
		}
		for (int i = 0; i < arrorders.length; i++) {
			OrderTransportDetailedParam o = new OrderTransportDetailedParam();
			try {
				o.setTransportNumber(arrorders[i]);
				_list2.add(o);
			} catch (Exception e) {
				return ResponseData.error("数据错误");
			}
		}
		if(ToolUtil.isEmpty(dispatchNumber)) {
			return ResponseData.error("数据错误");
		}
		ResponseData data = new ResponseData();
		User user = userAop.getUser();
		lock.lock();//获取锁
		try {
			BasicOperate basicOperate = basicOperateService.getById(operateId);
			data = transportDispatchService.batchassignNewDispatchNumber_driver(_list2,dispatchNumber,data,user,basicOperate,scanDress);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
		return data;
	}

	/**
	 * APP(页面二)查询订单号
	 */
	@ResponseBody
	@RequestMapping("/listOrder")
	public ResponseData listOrder(OrderTransportParam orderTransportParam,String carnumbger) {
		User user = userAop.getUser();
		orderTransportParam.setDeliverId(user.getDeliverId());
		orderTransportParam.setDeptId(user.getDeptId());
		String getUnit = orderTransportParam.getGetUnit();
		String getLocation = orderTransportParam.getGetLocation();
		if (getUnit!=null&&getUnit!="") {
			getUnit = getUnit.replace("& #40;", "(");
			getUnit = getUnit.replace("& #41;", ")");
			orderTransportParam.setGetUnit(getUnit);
		}
		if (getLocation!=null&&getLocation!="") {
			getLocation = getLocation.replace("& #40;", "(");
			getLocation = getLocation.replace("& #41;", ")");
			orderTransportParam.setGetLocation(getLocation);
		}
		orderTransportParam.setTstate("dispatch");
		List<OrderTransportResult> listyy = this.orderTransportService.findListBySpecNewNew(orderTransportParam,carnumbger,null);
		for (OrderTransportResult yr : listyy) {
			orderTransportParam.setGetLocationId(yr.getGetLocationId());
			List<OrderTransportResult> list = this.orderTransportService.findListBySpec(orderTransportParam,carnumbger,null);
			for (OrderTransportResult r : list) {
				TransportDispatchParam transportDispatchParam = new TransportDispatchParam();
				String token = "Wait";
				transportDispatchParam.setDispatchNumber("yichu");
				transportDispatchParam.setCarnumbger(carnumbger);
				transportDispatchParam.setTransportNumber(r.getTransportNumber());
				List<TransportDispatchResult> list2 = this.transportDispatchService.findgoodslistBySpec(transportDispatchParam,null,null,token,null);
				r.setListd(list2);
			}
			yr.setList(list);
		}
		return ResponseData.success(listyy);
	}

	/**
	 * APP(页面二)已完成 查询订单号
	 */
	@ResponseBody
	@RequestMapping("/listOrder2")
	public ResponseData listOrder2(OrderTransportParam orderTransportParam,String dispatchNumber) {
		User user = userAop.getUser();
		orderTransportParam.setDeptId(user.getDeptId());
		List<OrderTransportResult> listyy = this.orderTransportService.findListBySpecNewNewNew(orderTransportParam,dispatchNumber,user.getOperateId());
		for (OrderTransportResult yr : listyy) {
			orderTransportParam.setGetLocationId(yr.getGetLocationId());
			List<OrderTransportResult> list = this.orderTransportService.findListBySpecNewsss(orderTransportParam,dispatchNumber,user.getOperateId());
			for (OrderTransportResult r : list) {
				TransportDispatchParam transportDispatchParam = new TransportDispatchParam();
				transportDispatchParam.setTransportNumber(r.getTransportNumber());
				transportDispatchParam.setDispatchNumber(dispatchNumber);
				List<TransportDispatchResult> list2 = this.transportDispatchService.findgoodslistBySpec(transportDispatchParam,null,null,null,null);
				r.setListd(list2);
			}
			yr.setList(list);
		}
		return ResponseData.success(listyy);
	}

	/**
	 * APP 移除车辆
	 */
	@RequestMapping("/removeCarBySpec")
	@ResponseBody
	public ResponseData removeCarBySpec(String carnumbger) {
		ResponseData data = new ResponseData();
		return this.transportDispatchService.removeCarBySpecNew(null,null,carnumbger,data);
	}

	/**
	 * APP 移除订单
	 */
	@RequestMapping("/removeOrder")
	@ResponseBody
	public ResponseData removeOrder(String carnumbger,String transportNumber) {
		ResponseData data = new ResponseData();
		return this.transportDispatchService.removeOrderNew(transportNumber,carnumbger,data);
	}

	/**
	 * APP 移除商品
	 */
	@RequestMapping("/removeGoods")
	@ResponseBody
	public ResponseData removeGoods(String carnumbger,String transportNumber,Long goodsId) {
		ResponseData data = new ResponseData();
		return this.transportDispatchService.removeGoods(transportNumber,goodsId,carnumbger,data);
	}

	/**
	 * APP 修改派车 明细
	 */
	@RequestMapping("/editGoods")
	@ResponseBody
	public ResponseData editGoods(TransportDispatchParam transportDispatchParam) {
		ResponseData data = new ResponseData();
		return this.transportDispatchService.editGoods(transportDispatchParam,data);
	}

	/**
	 * APP 撤销派车单
	 */
	@RequestMapping("/removeDispatchNumberBySpec")
	@ResponseBody
	public ResponseData removeDispatchNumberBySpec(String dispatchNumber) {
		ResponseData data = new ResponseData();
		User user = userAop.getUser();
		return this.transportDispatchService.removeDispatchNumberBySpec(dispatchNumber,data,user);
	}

	/**
	 * APP 移除派车单商品
	 */
	@RequestMapping("/removeGoodsDispatch")
	@ResponseBody
	public ResponseData removeGoodsDispatch(TransportDispatchParam transportDispatchParam) {
		ResponseData data = new ResponseData();
		User user = userAop.getUser();
		return this.transportDispatchService.removeGoodsDispatch(transportDispatchParam,data,user);
	}

	/**
	 * APP 移除派车单订单
	 */
	@RequestMapping("/removeCustomerOrderDispatch")
	@ResponseBody
	public ResponseData removeCustomerOrderDispatch(TransportDispatchParam transportDispatchParam) {
		ResponseData data = new ResponseData();
		return this.transportDispatchService.removeCustomerOrderDispatch(transportDispatchParam,data);
	}

	/**
	 * APP 修改派车单商品
	 */
	@RequestMapping("/editGoodsDispatch")
	@ResponseBody
	public ResponseData editGoodsDispatch(TransportDispatchParam transportDispatchParam) {
		ResponseData data = new ResponseData();
		User user = userAop.getUser();
		return this.transportDispatchService.editGoodsDispatch(transportDispatchParam,data,user);
	}

	@Autowired
	private TDispatchService tDispatchService;

	@Autowired
	private TransportReceiptService transportReceiptService;

	@Autowired
	private TransportCostService transportCostService;

    @Autowired
    private BasicLoadingQuotationService basicLoadingQuotationService;

    @Autowired
    private BasicLinePriceService basicLinePriceService;

	@Autowired
    private BasicLineService basicLineService;

    /**
     * 计算费用
     */
	@RequestMapping("/countCost2")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public ResponseData countCost2(String dispatchNumber, String loadingType,String mileageTraveled) {  //调度单号  装车方
		User user = userAop.getUser();
		BigDecimal as = new BigDecimal("0");
		BigDecimal loadingMoney = new BigDecimal("0");  //创建2个计量对象赋值为0
		TDispatchParam tDispatchParam = new TDispatchParam();
		tDispatchParam.setDispatchNumber(dispatchNumber); //将调度单号填入
		TDispatchResult detail = this.tDispatchService.findBySpec(tDispatchParam, null); //根据调度单号查询信息
//		if (ToolUtil.isNotEmpty(loadingType)) { //如果装车方不为空
//			if (loadingType.equals("自装")) {//查询自装装车费
//				BasicLoadingQuotationParam loadingQuotationParam = new BasicLoadingQuotationParam();  //创建装车表对象
//				loadingQuotationParam.setOperateId(detail.getOperateId()); //填入传入调度单号项目id
//				BasicLoadingQuotationResult basicLoadingQuotationResult = basicLoadingQuotationService.findBySpec(loadingQuotationParam);
//				if (basicLoadingQuotationResult != null) {  //如果对象不为空
//					if (ToolUtil.isNotEmpty(basicLoadingQuotationResult.getPriceMode())) {  //如果计价方式不为空
//						if (basicLoadingQuotationResult.getPriceMode().equals("元/车")) { //如果计价方式 为此
//							if (ToolUtil.isNotEmpty(basicLoadingQuotationResult.getPrice())) { //计价标准
//								BigDecimal price = new BigDecimal(basicLoadingQuotationResult.getPrice()); //将计价标准赋值
//								if (price.compareTo(as) == 1) { // 如果计价标准大于0
//									loadingMoney = price;  // 让其等于0
//								}
//							}
//						}
//					}
//				}
//			}
//		}

		boolean eachOrderCost = false;//是否计算每单成本
		if(detail.getOperateId() != null) {
			BasicOperate basicOperate = basicOperateService.getById(detail.getOperateId());
			if(ToolUtil.isNotEmpty(basicOperate.getEachOrderCost())) {
				if(basicOperate.getEachOrderCost().equals("是")) {
					eachOrderCost = true;
				}
			}
		}

		List<TransportDispatchResult> dlist = new ArrayList<TransportDispatchResult>();//配置明细
		TransportDispatchParam transportDispatchParam = new TransportDispatchParam();
		transportDispatchParam.setDispatchNumber(detail.getDispatchNumber());
		transportDispatchParam.setCarId(detail.getCarId());
		transportDispatchParam.setDeptId(user.getDeptId());
		List<TransportDispatchResult> llist = null;
		//齐河好想来 项目编号 39
		if(detail.getOperateId() == 39L){
			llist = transportDispatchService.findLineListBySpecNew(transportDispatchParam,null,detail.getOperateId());//线路配置
		}else{
			llist = transportDispatchService.findLineListBySpec(transportDispatchParam,null,detail.getOperateId());//线路配置
		}

		if(eachOrderCost) {
			//齐河好想来 项目编号 39
			if(detail.getOperateId() == 39L){
				dlist = transportDispatchService.findOrderListBySpecNew(transportDispatchParam,null,detail.getOperateId());//订单配置
			}else{
				dlist = transportDispatchService.findOrderListBySpec(transportDispatchParam,null,detail.getOperateId());//订单配置
			}
		} else {
			dlist = llist;
		}

		List<TransportCost> costlist = new ArrayList<TransportCost>();
		BigDecimal totalConsultMoney = BigDecimal.ZERO; // 声明一个总价钱变量，初始值为0

		boolean sfyc = false;
		for (TransportDispatchResult r : dlist) {
			if (r.getLineId() == null) { //如果线路为空
				return ResponseData.error(r.getGetUnit() + "未设置所属线路");
			}
			BasicLine basicLine = basicLineService.getById(r.getLineId()); //获取线路id

			if(basicLine == null) {
				return ResponseData.error(r.getLineName() + "线路不存在");
			}
			if (!basicLine.getStatus().equals("1")) {  //如果线路被禁用
				return ResponseData.error(basicLine.getLineName() + "线路已被禁用");
			}

			BasicLinePriceParam basicLinePriceParam = new BasicLinePriceParam();
			basicLinePriceParam.setCarrierId(detail.getCarrierId());
			basicLinePriceParam.setLineId(r.getLineId());
			List<BasicLinePriceResult> basicLinePricelist = basicLinePriceService.getlineprice(basicLinePriceParam);//查询线路报价的方法
			if(basicLinePricelist.size()==0) {
				basicLinePriceParam.setCarrierId(null);
				basicLinePricelist = basicLinePriceService.getlineprice(basicLinePriceParam);
			}
			if(basicLinePricelist.size()==0) {//如果没有报价并且计算每单运费，就添加一条空费用明细
				if(eachOrderCost) {
					TransportCost addCost = new TransportCost();
					addCost.setDispatchNumber(dispatchNumber);
					addCost.setDeptId(detail.getDeptId());
					addCost.setDeliverId(detail.getDeliverId());
					addCost.setLineId(r.getLineId());
					addCost.setLineName(r.getLineName());
					addCost.setPriceName("运费");
					addCost.setNums(r.getTooDeployVolume());
					addCost.setV2("0");
					addCost.setMoney("0");
					addCost.setV1(r.getTransportNumber());
					costlist.add(addCost);
					continue;
				}
			}
			if (llist.size()>1 && basicLinePricelist.size()>1){
				sfyc=true;
			}
			for(BasicLinePriceResult r2 :basicLinePricelist){
				TransportCost addCost = new TransportCost();
				addCost.setDispatchNumber(dispatchNumber);
				addCost.setDeptId(detail.getDeptId());
				addCost.setDeliverId(detail.getDeliverId());
				addCost.setLineId(r.getLineId());
				addCost.setLineName(r.getLineName());
				addCost.setPriceName("运费");
				addCost.setNums(r.getTooDeployVolume());
				addCost.setV2("0");
				addCost.setMoney("0");
				if(eachOrderCost) {
					addCost.setV1(r.getTransportNumber());
				}

				BigDecimal b2 = BigDecimal.ZERO;
				if (ToolUtil.isNotEmpty(r2.getPrice())) {
					b2 = new BigDecimal(r2.getPrice());  //获取计价标准
				}

				BigDecimal volume = BigDecimal.ZERO;
				if (ToolUtil.isNotEmpty(r.getTooDeployVolume())) {
					volume = new BigDecimal(r.getTooDeployVolume());  //获取体积
				}

				BigDecimal num = BigDecimal.ZERO;
				if (ToolUtil.isNotEmpty(r.getTooDeployNum())) {
					num = new BigDecimal(r.getTooDeployNum()); //获取数量
				}

				BigDecimal licheng = BigDecimal.ZERO;
				if (ToolUtil.isNotEmpty(mileageTraveled)) {
					licheng = new BigDecimal(mileageTraveled); //获取公里数
				}

				BigDecimal csxx = BigDecimal.ZERO;
				if (ToolUtil.isNotEmpty(r2.getPriceCsxx())) {
					csxx = new BigDecimal(r2.getPriceCsxx()); //获取参数下限
				}

				BigDecimal cssx = BigDecimal.ZERO;
				if (ToolUtil.isNotEmpty(r2.getPriceCssx())) {
					cssx = new BigDecimal(r2.getPriceCssx()); //获取参数上限
				}

				BigDecimal priceQb = BigDecimal.ZERO;
				if (ToolUtil.isNotEmpty(r2.getPriceQb())) {
					priceQb = new BigDecimal(r2.getPriceQb()); //获取起步价
				}

				BigDecimal priceQbds = BigDecimal.ZERO;
				if (ToolUtil.isNotEmpty(r2.getPriceQbds())) {
					priceQbds = new BigDecimal(r2.getPriceQbds()); //获取起步点数
				}

				BigDecimal prceQbcd = BigDecimal.ZERO;
				if (ToolUtil.isNotEmpty(r2.getPrceQbcd())) {
					prceQbcd = new BigDecimal(r2.getPrceQbcd()); //获取超点费用
				}

				boolean chexingflag = true;//判断报价车型是否一直
				if(ToolUtil.isNotEmpty(r2.getCarType())) {
					if(ToolUtil.isNotEmpty(detail.getChexing())) {
						if(!r2.getCarType().equals(detail.getChexing())) {
							chexingflag = false;
						}
					}
				}

				if(chexingflag) {
					if(ToolUtil.isEmpty(r2.getPriceType())||r2.getPriceType().equals("固定")){
						if (r2.getPriceMode().equals("元/m³")){
							BigDecimal b2mulvolume = volume.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
							totalConsultMoney = totalConsultMoney.add(b2mulvolume);
							
							addCost.setPriceMode(r2.getPriceMode());
							addCost.setPrice(b2+"");
							addCost.setNums(volume+"");
							addCost.setMoney(b2mulvolume+"");
						}
						if(r2.getPriceMode().equals("元/件")){
							BigDecimal b2num = num.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
							totalConsultMoney = totalConsultMoney.add(b2num);
							
							addCost.setPriceMode(r2.getPriceMode());
							addCost.setPrice(b2+"");
							addCost.setNums(num+"");
							addCost.setMoney(b2num+"");
						}
						if (r2.getPriceMode().equals("元/车")){
							if (sfyc){
								totalConsultMoney = BigDecimal.ZERO;
							}else{
								totalConsultMoney = totalConsultMoney.add(b2);
							}
							
							addCost.setPriceMode(r2.getPriceMode());
							addCost.setPrice(b2+"");
							addCost.setNums("1");
							addCost.setMoney(b2+"");
						}
						if (r2.getPriceMode().equals("元/公里")){
							if (licheng.compareTo(as) == 1) {
								BigDecimal b2licheng = licheng.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
								if (sfyc){
									totalConsultMoney = BigDecimal.ZERO;
								} else {
									totalConsultMoney = totalConsultMoney.add(b2licheng);
								}
								
								addCost.setPriceMode(r2.getPriceMode());
								addCost.setPrice(b2+"");
								addCost.setNums(licheng+"");
								addCost.setMoney(b2licheng+"");
							}
						}
						if (r2.getPriceMode().equals("元/点")){
							addCost.setPriceMode(r2.getPriceMode());
							addCost.setPrice(priceQb+"");
							addCost.setV3(priceQbds+"");
							addCost.setV4(prceQbcd+"");
							BigDecimal money = priceQb;
							
							if (sfyc){
								totalConsultMoney = BigDecimal.ZERO;
							} else {
								totalConsultMoney = totalConsultMoney.add(priceQb);
							}
							
							// 计算是否超点
							if(priceQbds.compareTo(as) == 1 && prceQbcd.compareTo(as) == 1) {
								TransportDispatchParam countppp = new TransportDispatchParam();
								countppp.setDispatchNumber(detail.getDispatchNumber());
								countppp.setLineId(r.getLineId());
								Integer countgg = transportDispatchService.countGetUnit(countppp);//合计该线路下  门店数
								if(countgg != null && countgg>0) {
									addCost.setNums(countgg+"");
									BigDecimal bigcountgg = new BigDecimal(countgg);
									if(bigcountgg.compareTo(priceQbds) == 1) {//如果门店数 大于 起步点数
										BigDecimal countsubqbds = bigcountgg.subtract(priceQbds);
										BigDecimal cmcd = countsubqbds.multiply(prceQbcd).setScale(3, BigDecimal.ROUND_HALF_DOWN);
										money = money.add(cmcd);
										if (sfyc){
											totalConsultMoney = BigDecimal.ZERO;
										} else {
											totalConsultMoney = totalConsultMoney.add(cmcd);
										}
									}
								}
							}
							addCost.setMoney(money+"");
						}
					}
					if(ToolUtil.isNotEmpty(r2.getPriceType())&&r2.getPriceType().equals("范围")) {
						//参数范围
						if (r2.getPriceCsbz().equals("按件数")) {
							BigDecimal fwajs = BigDecimal.ZERO;
							if(eachOrderCost) {
								for (TransportDispatchResult llr : llist) {
									if(llr.getLineId().equals(r.getLineId())) {
										fwajs = new BigDecimal(llr.getTooDeployNum());
										break;
									}
								}
							} else {
								fwajs = new BigDecimal(r.getTooDeployNum());
							}
							if(fwajs.compareTo(as) == 1) {
								if ((fwajs.compareTo(csxx) != -1) && (fwajs.compareTo(cssx) != 1)){ //大于等于参数下限 效应等于参数上限
									if (r2.getPriceMode().equals("元/m³")){
										BigDecimal b2mulvolume = volume.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
										if (sfyc){
											totalConsultMoney = BigDecimal.ZERO;
										} else {
											totalConsultMoney = totalConsultMoney.add(b2mulvolume);
										}
										
										addCost.setPriceMode(r2.getPriceMode());
										addCost.setPrice(b2+"");
										addCost.setNums(volume+"");
										addCost.setMoney(b2mulvolume+"");
									}
									if(r2.getPriceMode().equals("元/件")){
										BigDecimal b2num = num.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
										if (sfyc){
											totalConsultMoney = BigDecimal.ZERO;
										} else {
											totalConsultMoney = totalConsultMoney.add(b2num);
										}
										addCost.setPriceMode(r2.getPriceMode());
										addCost.setPrice(b2+"");
										addCost.setNums(num+"");
										addCost.setMoney(b2num+"");
									}
									if (r2.getPriceMode().equals("元/车")){
										if (sfyc){
											totalConsultMoney = BigDecimal.ZERO;
										} else {
											totalConsultMoney = totalConsultMoney.add(b2);
										}
										
										addCost.setPriceMode(r2.getPriceMode());
										addCost.setPrice(b2+"");
										addCost.setNums("1");
										addCost.setMoney(b2+"");
									}
									if (r2.getPriceMode().equals("元/公里")){
										if (licheng.compareTo(as) == 1) {
											BigDecimal b2licheng = licheng.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
											if (sfyc){
												totalConsultMoney = BigDecimal.ZERO;
											} else {
												totalConsultMoney = totalConsultMoney.add(b2licheng);
											}
											
											addCost.setPriceMode(r2.getPriceMode());
											addCost.setPrice(b2+"");
											addCost.setNums(licheng+"");
											addCost.setMoney(b2licheng+"");
										}
									}
									if (r2.getPriceMode().equals("元/点")){
										addCost.setPriceMode(r2.getPriceMode());
										addCost.setPrice(priceQb+"");
										addCost.setV3(priceQbds+"");
										addCost.setV4(prceQbcd+"");
										BigDecimal money = priceQb;
										if (sfyc){
											totalConsultMoney = BigDecimal.ZERO;
										} else {
											totalConsultMoney = totalConsultMoney.add(priceQb);
										}
										
										// 计算是否超点
										if(priceQbds.compareTo(as) == 1 && prceQbcd.compareTo(as) == 1) {
											TransportDispatchParam countppp = new TransportDispatchParam();
											countppp.setDispatchNumber(detail.getDispatchNumber());
											countppp.setLineId(r.getLineId());
											Integer countgg = transportDispatchService.countGetUnit(countppp);//合计该线路下  门店数
											if(countgg != null && countgg>0) {
												addCost.setNums(countgg+"");
												BigDecimal bigcountgg = new BigDecimal(countgg);
												if(bigcountgg.compareTo(priceQbds) == 1) {//如果门店数 大于 起步点数
													BigDecimal countsubqbds = bigcountgg.subtract(priceQbds);
													BigDecimal cmcd = countsubqbds.multiply(prceQbcd).setScale(3, BigDecimal.ROUND_HALF_DOWN);
													money = money.add(cmcd);
													if (sfyc){
														totalConsultMoney = BigDecimal.ZERO;
													} else {
														totalConsultMoney = totalConsultMoney.add(cmcd);
													}
												}
											}
										}
										addCost.setMoney(money+"");
									}
								}
								
							}
						}
						if (r2.getPriceCsbz().equals("按体积m³")) {
							BigDecimal fwatj = BigDecimal.ZERO;
							if(eachOrderCost) {
								for (TransportDispatchResult llr : llist) {
									if(llr.getLineId().equals(r.getLineId())) {
										fwatj = new BigDecimal(llr.getTooDeployVolume());
										break;
									}
								}
							} else {
								fwatj = new BigDecimal(r.getTooDeployVolume());
							}
							
							if ((fwatj.compareTo(csxx) != -1) && (fwatj.compareTo(cssx) != 1)){ //大于等于参数下限 小于等于参数上限
								if (r2.getPriceMode().equals("元/m³")){
									BigDecimal b2mulvolume = volume.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
									if (sfyc){
										totalConsultMoney = BigDecimal.ZERO;
									}else{
										totalConsultMoney = totalConsultMoney.add(b2mulvolume);
									}
									
									addCost.setPriceMode(r2.getPriceMode());
									addCost.setPrice(b2+"");
									addCost.setNums(volume+"");
									addCost.setMoney(b2mulvolume+"");
								}
								if(r2.getPriceMode().equals("元/件")){
									BigDecimal b2num = num.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
									if (sfyc){
										totalConsultMoney = BigDecimal.ZERO;
									}else{
										totalConsultMoney = totalConsultMoney.add(b2num);
									}
									
									addCost.setPriceMode(r2.getPriceMode());
									addCost.setPrice(b2+"");
									addCost.setNums(num+"");
									addCost.setMoney(b2num+"");
								}
								if (r2.getPriceMode().equals("元/车")){
									if (sfyc){
										totalConsultMoney = BigDecimal.ZERO;
									}else{
										totalConsultMoney = totalConsultMoney.add(b2);
									}
									
									addCost.setPriceMode(r2.getPriceMode());
									addCost.setPrice(b2+"");
									addCost.setNums("1");
									addCost.setMoney(b2+"");
								}
								if (r2.getPriceMode().equals("元/公里")){
									if (licheng.compareTo(as) == 1) {
										BigDecimal b2licheng = licheng.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
										if (sfyc){
											totalConsultMoney = BigDecimal.ZERO;
										} else {
											totalConsultMoney = totalConsultMoney.add(b2licheng);
										}
										
										addCost.setPriceMode(r2.getPriceMode());
										addCost.setPrice(b2+"");
										addCost.setNums(licheng+"");
										addCost.setMoney(b2licheng+"");
									}
								}
								if (r2.getPriceMode().equals("元/点")){
									addCost.setPriceMode(r2.getPriceMode());
									addCost.setPrice(priceQb+"");
									addCost.setV3(priceQbds+"");
									addCost.setV4(prceQbcd+"");
									BigDecimal money = priceQb;
									
									if (sfyc){
										totalConsultMoney = BigDecimal.ZERO;
									} else {
										totalConsultMoney = totalConsultMoney.add(priceQb);
									}
									// 计算是否超点
									if(priceQbds.compareTo(as) == 1 && prceQbcd.compareTo(as) == 1) {
										TransportDispatchParam countppp = new TransportDispatchParam();
										countppp.setDispatchNumber(detail.getDispatchNumber());
										countppp.setLineId(r.getLineId());
										Integer countgg = transportDispatchService.countGetUnit(countppp);//合计该线路下  门店数
										if(countgg != null && countgg>0) {
											addCost.setNums(countgg+"");
											BigDecimal bigcountgg = new BigDecimal(countgg);
											if(bigcountgg.compareTo(priceQbds) == 1) {//如果门店数 大于 起步点数
												BigDecimal countsubqbds = bigcountgg.subtract(priceQbds);
												BigDecimal cmcd = countsubqbds.multiply(prceQbcd).setScale(3, BigDecimal.ROUND_HALF_DOWN);
												money = money.add(cmcd);
												if (sfyc){
													totalConsultMoney = BigDecimal.ZERO;
												} else {
													totalConsultMoney = totalConsultMoney.add(cmcd);
												}
											}
										}
									}
									addCost.setMoney(money+"");
								}
							}
						}
						if (r2.getPriceCsbz().equals("按公里")) {
							if (ToolUtil.isNotEmpty(licheng)) {
								if ((licheng.compareTo(csxx) != -1) && (licheng.compareTo(cssx) != 1)){ //大于等于参数下限 小于等于参数上限
									if (r2.getPriceMode().equals("元/m³")){
										BigDecimal b2mulvolume = volume.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
										if (sfyc){
											totalConsultMoney = BigDecimal.ZERO;
										} else {
											totalConsultMoney = totalConsultMoney.add(b2mulvolume);
										}
										
										addCost.setPriceMode(r2.getPriceMode());
										addCost.setPrice(b2+"");
										addCost.setNums(volume+"");
										addCost.setMoney(b2mulvolume+"");
									}
									if(r2.getPriceMode().equals("元/件")){
										BigDecimal b2num = num.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
										if (sfyc){
											totalConsultMoney = BigDecimal.ZERO;
										} else {
											totalConsultMoney = totalConsultMoney.add(b2num);
										}
										
										addCost.setPriceMode(r2.getPriceMode());
										addCost.setPrice(b2+"");
										addCost.setNums(num+"");
										addCost.setMoney(b2num+"");
									}
									if (r2.getPriceMode().equals("元/车")){
										if (sfyc){
											totalConsultMoney = BigDecimal.ZERO;
										} else {
											totalConsultMoney = totalConsultMoney.add(b2);
										}
										
										addCost.setPriceMode(r2.getPriceMode());
										addCost.setPrice(b2+"");
										addCost.setNums("1");
										addCost.setMoney(b2+"");
									}
									if (r2.getPriceMode().equals("元/公里")){
										if (licheng.compareTo(as) == 1) {
											BigDecimal b2licheng = licheng.multiply(b2).setScale(3, BigDecimal.ROUND_HALF_DOWN);
											if (sfyc){
												totalConsultMoney = BigDecimal.ZERO;
											} else {
												totalConsultMoney = totalConsultMoney.add(b2licheng);
											}
											
											addCost.setPriceMode(r2.getPriceMode());
											addCost.setPrice(b2+"");
											addCost.setNums(licheng+"");
											addCost.setMoney(b2licheng+"");
										}
									}
									if (r2.getPriceMode().equals("元/点")){
										addCost.setPriceMode(r2.getPriceMode());
										addCost.setPrice(priceQb+"");
										addCost.setV3(priceQbds+"");
										addCost.setV4(prceQbcd+"");
										BigDecimal money = priceQb;
										if (sfyc){
											totalConsultMoney = BigDecimal.ZERO;
										} else {
											totalConsultMoney = totalConsultMoney.add(priceQb);
										}
										// 计算是否超点
										if(priceQbds.compareTo(as) == 1 && prceQbcd.compareTo(as) == 1) {
											TransportDispatchParam countppp = new TransportDispatchParam();
											countppp.setDispatchNumber(detail.getDispatchNumber());
											countppp.setLineId(r.getLineId());
											Integer countgg = transportDispatchService.countGetUnit(countppp);//合计该线路下  门店数
											if(countgg != null && countgg>0) {
												addCost.setNums(countgg+"");
												BigDecimal bigcountgg = new BigDecimal(countgg);
												if(bigcountgg.compareTo(priceQbds) == 1) {//如果门店数 大于 起步点数
													BigDecimal countsubqbds = bigcountgg.subtract(priceQbds);
													BigDecimal cmcd = countsubqbds.multiply(prceQbcd).setScale(3, BigDecimal.ROUND_HALF_DOWN);
													money = money.add(cmcd);
													if (sfyc){
														totalConsultMoney = BigDecimal.ZERO;
													} else {
														totalConsultMoney = totalConsultMoney.add(cmcd);
													}
												}
											}
										}
										addCost.setMoney(money+"");
									}
								}
							}
						}
					}
				}
				costlist.add(addCost);
			}
			//装车费
			BigDecimal num = BigDecimal.ZERO;
			if (ToolUtil.isNotEmpty(r.getTooDeployNum())) {
				num = new BigDecimal(r.getTooDeployNum()); //获取数量
			}
			BigDecimal volume = BigDecimal.ZERO;
			if (ToolUtil.isNotEmpty(r.getTooDeployVolume())) {
				volume = new BigDecimal(r.getTooDeployVolume());  //获取体积
			}
			BasicLoadingQuotationParam loadingQuotationParam = new BasicLoadingQuotationParam();  //创建装车表对象
			loadingQuotationParam.setOperateId(detail.getOperateId()); //填入传入调度单号项目id
			loadingQuotationParam.setCarrierId(detail.getCarrierId()); //承运商
//				loadingQuotationParam.setLineId(r.getLineId());//线路
			loadingQuotationParam.setLoadingType(loadingType); //装运方
			BasicLoadingQuotationResult basicLoadingQuotationResult = basicLoadingQuotationService.findBySpec(loadingQuotationParam);
			if(basicLoadingQuotationResult != null && ToolUtil.isNotEmpty(basicLoadingQuotationResult.getPrice())){
				if("元/车".equals(basicLoadingQuotationResult.getPriceMode())){
					BigDecimal price = new BigDecimal(basicLoadingQuotationResult.getPrice());
					loadingMoney = loadingMoney.add(price.setScale(3, BigDecimal.ROUND_HALF_DOWN));
				}else if("元/件".equals(basicLoadingQuotationResult.getPriceMode())){
					BigDecimal price = new BigDecimal(basicLoadingQuotationResult.getPrice());
					loadingMoney = loadingMoney.add(price.multiply(num).setScale(3, BigDecimal.ROUND_HALF_DOWN));
				}else if("元/m³".equals(basicLoadingQuotationResult.getPriceMode())){
					BigDecimal price = new BigDecimal(basicLoadingQuotationResult.getPrice());
					loadingMoney = loadingMoney.add(price.multiply(volume).setScale(3, BigDecimal.ROUND_HALF_DOWN));
				}
			}
		}
		//临时车不计算运费
//		if(detail.getCarrierName() != null && detail.getCarrierName().contains("临时车") && detail.getOperateId() == 39){
//			totalConsultMoney = as;
//		}
		tDispatchService.lambdaUpdate()
				.eq(TDispatch::getDispatchNumber,dispatchNumber)
				.set(TDispatch::getMileageTraveled, mileageTraveled)
				.set(TDispatch::getConsultMoney,totalConsultMoney)
				.set(TDispatch::getFreightMoney,totalConsultMoney)
				.set(TDispatch::getLoadingType, loadingType)
				.set(TDispatch::getLoadingMoney, loadingMoney)
				.set(TDispatch::getCalculateShippingCost, "是")
				.update();
		if(costlist.size()>0) {
			// 移除null值
//			costlist.removeIf(item -> item.getPriceMode() == null);
			TransportCostParam delete = new TransportCostParam();
			delete.setDispatchNumber(dispatchNumber);
			transportCostService.deleteBySpec(delete);
			transportCostService.saveBatch(costlist);
		}
		tDispatchParam.setConsultMoney(totalConsultMoney+"");
		if(detail.getCarrierName() != null && detail.getCarrierName().contains("临时车")){
			tDispatchParam.setFreightMoney("");
		}else{
			tDispatchParam.setFreightMoney(totalConsultMoney+"");
		}
		tDispatchParam.setLoadingMoney(loadingMoney+"");
		return ResponseData.success(tDispatchParam);
	}

	/**
	 * 确定运费
	 */
	@RequestMapping("/editItem")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public ResponseData editItem(TDispatchParam tDispatchParam,String[] loadingNumbers) {
		String message = "";
		TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam,null);
		BasicOperate basicOperate = basicOperateService.getById(dispatchResult.getOperateId());
		if(dispatchResult != null) {
			if(ToolUtil.isNotEmpty(dispatchResult.getCalculateShippingCost())&&!dispatchResult.getCalculateShippingCost().equals("是")) {
				return ResponseData.error("请生成运费");
			}
			if(dispatchResult.getTstate().equals("待定价")||dispatchResult.getTstate().equals("驳回")) {
				User user = userAop.getUser();
				if(tDispatchParam.getLoadingType().equals("自装")) {
					tDispatchParam.setLoadingPersonnel("自装");
				} else if (tDispatchParam.getLoadingType().equals("仓库")) {
					if(loadingNumbers != null) {
						String sloadingPersonnel = "";
						String loadingNumbersp = "";
						for (int i = 0; i < loadingNumbers.length; i++) {
							String loadingNumber = loadingNumbers[i];
							if(ToolUtil.isNotEmpty(loadingNumber)) {
								TransportStevedoreSigninParam stevedoreSigninParam = new TransportStevedoreSigninParam();
								stevedoreSigninParam.setAuditBy(loadingNumber);
								stevedoreSigninParam.setDeptId(user.getDeptId());
								TransportStevedoreSigninResult signres = transportStevedoreSigninService.findBySpec(stevedoreSigninParam, user.getOperateId());
								if(signres != null) {
									sloadingPersonnel += signres.getAuditTime();
									loadingNumbersp += loadingNumber;
									if(loadingNumbers.length != i+1) {
										sloadingPersonnel += "+";
										loadingNumbersp += ",";
									}
								}
							}
						}
						tDispatchParam.setLoadingNumber(loadingNumbersp);
						tDispatchParam.setLoadingPersonnel(sloadingPersonnel);
					}
				}
				BigDecimal as = new BigDecimal(0);

				//计算每单实际金额
				BigDecimal freightMoney = new BigDecimal(tDispatchParam.getFreightMoney());
				BigDecimal money = new BigDecimal(tDispatchParam.getFreightMoney());
				BigDecimal loadingMoney = new BigDecimal("0");
				if(ToolUtil.isNotEmpty(tDispatchParam.getLoadingMoney())) {//装车费
					loadingMoney = new BigDecimal(tDispatchParam.getLoadingMoney());
					if(loadingMoney.compareTo(as) == 1) {
						money = money.add(loadingMoney).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					}
				}
				if(ToolUtil.isNotEmpty(basicOperate.getEachOrderCost())&&basicOperate.getEachOrderCost().equals("是")) {
					if(freightMoney.compareTo(as) == 0) {
						TransportCostParam costParam = new TransportCostParam();
						costParam.setDispatchNumber(dispatchResult.getDispatchNumber());
						List<TransportCostResult> list = transportCostService.findListBySpecS(costParam);
						for (TransportCostResult cr : list) {
							costParam.setV2("0");
							costParam.setId(cr.getId());
							transportCostService.update(costParam);
						}
					} else {
						BigDecimal consultMoney = new BigDecimal(0);
						if(ToolUtil.isNotEmpty(dispatchResult.getConsultMoney())) {
							consultMoney = new BigDecimal(dispatchResult.getConsultMoney());
						}
						if(freightMoney.compareTo(consultMoney) != 0) {
							BigDecimal toovolume = new BigDecimal(dispatchResult.getToovolume());//总体积
							BigDecimal consultPrice = freightMoney.divide(toovolume,8,BigDecimal.ROUND_HALF_DOWN);//金额 / 总体积 =  实际单方价格
							TransportCostParam costParam = new TransportCostParam();
							costParam.setDispatchNumber(dispatchResult.getDispatchNumber());
							List<TransportCostResult> list = transportCostService.findListBySpecS(costParam);
							for (TransportCostResult cr : list) {
								BigDecimal nums = new BigDecimal(cr.getNums());//体积
								BigDecimal dmoney = nums.multiply(consultPrice).setScale(3, BigDecimal.ROUND_HALF_DOWN);//订单体积 * 实际单方价格 = 订单实际价格
								costParam.setV2(dmoney.toString());
								costParam.setId(cr.getId());
								transportCostService.update(costParam);
							}
						}
					}
				} else {
					TransportCostParam costParam = new TransportCostParam();
					costParam.setDispatchNumber(dispatchResult.getDispatchNumber());
					List<TransportCostResult> list = transportCostService.findListBySpecS(costParam);
					for (TransportCostResult cr : list) {
						costParam.setV2("0");
						costParam.setId(cr.getId());
						transportCostService.update(costParam);
					}
				}

				//根据封箱数量  更新派车明细换算数量
//				if(ToolUtil.isNotEmpty(tDispatchParam.getSealingNumber())) {
//					BigDecimal sealingNumber = new BigDecimal(tDispatchParam.getSealingNumber());
//					TransportDispatchParam clParam = new TransportDispatchParam();
//					clParam.setDispatchNumber(tDispatchParam.getDispatchNumber());
//					List<TransportDispatchResult> cllist = transportDispatchService.findClListBySpec(clParam);//拆零派车明细
//					if(cllist.size() > 0) {
//						BigDecimal dispatchs = new BigDecimal(cllist.size());
//						BigDecimal newmatrixingNumber = sealingNumber.divide(dispatchs,3,BigDecimal.ROUND_HALF_DOWN);
//						UpdateWrapper<TransportDispatch> updateWrapper = new UpdateWrapper<TransportDispatch>();
//						updateWrapper.set("matrixing_number", newmatrixingNumber);
//						updateWrapper.eq("dispatch_number", tDispatchParam.getDispatchNumber());
//						updateWrapper.eq("goods_number", "cl1");
//						transportDispatchService.update(updateWrapper);
//					}
//				}

//        		if(ToolUtil.isNotEmpty(dispatchResult.getConsultMoney())){
//        			BigDecimal consultMoney = new BigDecimal(dispatchResult.getConsultMoney());
//        			if(consultMoney.compareTo(as) == 1) {//参考价大于0
//        				if(freightMoney.compareTo(consultMoney) == 1) {//金额大于  参考价
//        	            	tDispatchParam.setId(dispatchResult.getId());
//        	            	tDispatchParam.setTstate("待审核");
//        	                this.tDispatchService.update(tDispatchParam);
//        	                ResponseData data = new ResponseData();
//        	                data.setSuccess(true);
//        	                data.setCode(403);
//                    		message += "请等待审核";
//        	                data.setMessage(message);
//        	                return data;
//        				}
//        			}
//        		}
//        		if(ToolUtil.isNotEmpty(tDispatchParam.getXiechefei())) {
//        			BigDecimal xiechefei = new BigDecimal(tDispatchParam.getXiechefei());
//        			money = money.add(xiechefei).setScale(3, BigDecimal.ROUND_HALF_UP);
//        		}
				TDispatchParam param = new TDispatchParam();
				param.setDeptId(user.getDeptId());
				param.setDeliverId(user.getDeliverId());
				param.setFulllv(tDispatchParam.getStartDate());
				Integer trainNumber = tDispatchService.countCarnumber(param,user.getOperateId());//查询发运车次
				tDispatchParam.setMoney(money.toString());
				if(trainNumber == null) {
					tDispatchParam.setTrainNumber("1");
				} else {
					tDispatchParam.setTrainNumber((trainNumber+1)+"");
				}

				TransportMsgParam dcqd = new TransportMsgParam();
				dcqd.setV3(dispatchResult.getCarId()+"");
				dcqd.setDeptId(user.getDeptId());
				dcqd.setStatus("到仓签到");
				TransportMsgResult msgResult = transportMsgService.findDcqdBySpec(dcqd,user.getOperateId());
				if(msgResult != null) {
					TransportMsgParam transportMsgParam = new TransportMsgParam();
					transportMsgParam.setDispatchNumber(dispatchResult.getDispatchNumber());
					transportMsgParam.setStatus("到仓装车");
					transportMsgParam.setMsgType("司机");
					transportMsgParam.setContent(dispatchResult.getCarnumber()+"已到达仓库开始装车。"+"当前定位："+msgResult.getContent());
					transportMsgParam.setTimes(msgResult.getTimes());
					transportMsgParam.setCreateUsername(msgResult.getCreateUsername());
					transportMsgParam.setDeliverId(user.getDeliverId());
					transportMsgParam.setDeptId(user.getDeptId());
					transportMsgParam.setSfyz("是");
                    transportMsgParam.setOpenId(msgResult.getOpenId());
					transportMsgService.add(transportMsgParam);
					
					tDispatchParam.setId(dispatchResult.getId());
					tDispatchParam.setTstate("待发运");
					this.tDispatchService.update(tDispatchParam);
				} else {
            		if(ToolUtil.isNotEmpty(basicOperate.getQdDriver()) && basicOperate.getQdDriver().equals("是")) {
    					message += "检测到还未签到！请下次到仓先进行签到";
    					TransportMsgParam transportMsgParam = new TransportMsgParam();
    					transportMsgParam.setStatus("到仓签到");
    					transportMsgParam.setMsgType("系统");
    					transportMsgParam.setTimes(tDispatchParam.getStartDate());
    					transportMsgParam.setV1(dispatchResult.getCarnumber());
    					transportMsgParam.setV2(dispatchResult.getSijidianhua());
    					transportMsgParam.setV3(dispatchResult.getCarId()+"");
    					transportMsgParam.setCreateUsername(dispatchResult.getSiji()+",系统自动补签");
    					transportMsgParam.setDeptId(user.getDeptId());
    					transportMsgParam.setDeliverId(user.getDeliverId());
    					transportMsgService.add(transportMsgParam);

    					TransportMsgParam transportMsgParam2 = new TransportMsgParam();
    					transportMsgParam2.setDispatchNumber(dispatchResult.getDispatchNumber());
    					transportMsgParam2.setStatus("到仓装车");
    					transportMsgParam2.setMsgType("系统");
    					transportMsgParam2.setContent(dispatchResult.getCarnumber()+"已到达仓库开始装车。");
    					transportMsgParam2.setTimes(tDispatchParam.getStartDate());
    					transportMsgParam2.setCreateUsername(user.getName());
    					transportMsgParam2.setDeliverId(user.getDeliverId());
    					transportMsgParam2.setDeptId(user.getDeptId());
    					transportMsgService.add(transportMsgParam2);
        				
                    	tDispatchParam.setId(dispatchResult.getId());
                    	tDispatchParam.setTstate("待发运");
                        this.tDispatchService.update(tDispatchParam);
            		} else {
                    	tDispatchParam.setId(dispatchResult.getId());
                    	tDispatchParam.setTstate("已定价");
                        this.tDispatchService.update(tDispatchParam);
            		}
				}
			}
		}
		ResponseData data = new ResponseData();
		data.setSuccess(true);
		data.setMessage(message);
		return data;
	}

	/**
	 *定价审核
	 *通过
	 */
	@RequestMapping("/tongguo")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public ResponseData tongguo(TDispatchParam tDispatchParam) {
		User user = userAop.getUser();
		String message = "";
		TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam,null);
		BasicOperate basicOperate = basicOperateService.getById(dispatchResult.getOperateId());
		BigDecimal money = new BigDecimal(dispatchResult.getFreightMoney());
		if(ToolUtil.isNotEmpty(dispatchResult.getXiechefei())) {
			BigDecimal xiechefei = new BigDecimal(dispatchResult.getXiechefei());
			money = money.add(xiechefei).setScale(3, BigDecimal.ROUND_HALF_UP);
		}

		tDispatchParam.setId(dispatchResult.getId());
		tDispatchParam.setMoney(money.toString());
		tDispatchParam.setExamineName(user.getName());
		tDispatchParam.setExamineTimes(DateUtil.getDateS());

		TDispatchParam param = new TDispatchParam();
		param.setDeptId(user.getDeptId());
		param.setDeliverId(user.getDeliverId());
		param.setFulllv(dispatchResult.getStartDate());
		Integer trainNumber = tDispatchService.countCarnumber(param,user.getOperateId());//查询今日发运车次
		if(trainNumber == null) {
			tDispatchParam.setTrainNumber("1");
		} else {
			tDispatchParam.setTrainNumber((trainNumber+1)+"");
		}

		TransportMsgParam dcqd = new TransportMsgParam();
		dcqd.setV3(dispatchResult.getCarId()+"");
		dcqd.setDeptId(user.getDeptId());
		dcqd.setStatus("到仓签到");
		TransportMsgResult msgResult = transportMsgService.findDcqdBySpec(dcqd,user.getOperateId());
		if(msgResult != null) {
			TransportMsgParam transportMsgParam = new TransportMsgParam();
			transportMsgParam.setDispatchNumber(dispatchResult.getDispatchNumber());
			transportMsgParam.setStatus("到仓装车");
			transportMsgParam.setMsgType("司机");
			transportMsgParam.setContent(dispatchResult.getCarnumber()+"已到达仓库开始装车。"+"当前定位："+msgResult.getContent());
			transportMsgParam.setTimes(msgResult.getTimes());
			transportMsgParam.setCreateUsername(msgResult.getCreateUsername());
			transportMsgParam.setDeliverId(user.getDeliverId());
			transportMsgParam.setDeptId(user.getDeptId());
			transportMsgParam.setSfyz("是");
            transportMsgParam.setOpenId(msgResult.getOpenId());
			transportMsgService.add(transportMsgParam);

			tDispatchParam.setTstate("待发运");
			tDispatchService.update(tDispatchParam);
		} else {
    		if(ToolUtil.isNotEmpty(basicOperate.getQdDriver()) && basicOperate.getQdDriver().equals("是")) {
    			message += "检测到还未签到！请下次到仓先进行签到";
    			TransportMsgParam transportMsgParam = new TransportMsgParam();
    			transportMsgParam.setStatus("到仓签到");
    			transportMsgParam.setMsgType("系统");
    			transportMsgParam.setTimes(dispatchResult.getStartDate());
    			transportMsgParam.setV1(dispatchResult.getCarnumber());
    			transportMsgParam.setV2(dispatchResult.getSijidianhua());
    			transportMsgParam.setV3(dispatchResult.getCarId()+"");
    			transportMsgParam.setCreateUsername(dispatchResult.getSiji()+",系统自动补签");
    			transportMsgParam.setDeptId(user.getDeptId());
    			transportMsgParam.setDeliverId(user.getDeliverId());
    			transportMsgService.add(transportMsgParam);

    			TransportMsgParam transportMsgParam2 = new TransportMsgParam();
    			transportMsgParam2.setDispatchNumber(dispatchResult.getDispatchNumber());
    			transportMsgParam2.setStatus("到仓装车");
    			transportMsgParam2.setMsgType("系统");
    			transportMsgParam2.setContent(dispatchResult.getCarnumber()+"已到达仓库开始装车。");
    			transportMsgParam2.setTimes(dispatchResult.getStartDate());
    			transportMsgParam2.setCreateUsername(user.getName());
    			transportMsgParam2.setDeliverId(user.getDeliverId());
    			transportMsgParam2.setDeptId(user.getDeptId());
    			transportMsgService.add(transportMsgParam2);

    			tDispatchParam.setTstate("待发运");
    			tDispatchService.update(tDispatchParam);
    		} else {
    			tDispatchParam.setTstate("已定价");
    			tDispatchService.update(tDispatchParam);
    		}
		}
		ResponseData data = new ResponseData();
		data.setSuccess(true);
		data.setMessage(message);
		return data;
	}

	/**
	 *定价审核
	 *驳回
	 */
	@RequestMapping("/bohui")
	@ResponseBody
	public ResponseData bohui(TDispatchParam tDispatchParam) {
		User user = userAop.getUser();
		TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam,null);
		tDispatchParam.setId(dispatchResult.getId());
		tDispatchParam.setTstate("驳回");
		tDispatchParam.setExamineName(user.getName());
		tDispatchParam.setExamineTimes(DateUtil.getDateS());
		tDispatchService.update(tDispatchParam);
		return ResponseData.success();
	}

	/**
	 * 修改 地址经纬度
	 */
	@RequestMapping("/editAddress")
	@ResponseBody
	public ResponseData editAddress(BasicAddressParam basicAddressParam) {
		Boolean falg = false;
		BasicAddress basicAddress = basicAddressService.getById(basicAddressParam.getId());
		if(ToolUtil.isEmpty(basicAddress.getSwitchBj())) {
			basicAddress.setSwitchBj("100");
			falg = true;
		}
		if(ToolUtil.isEmpty(basicAddress.getSwitchBj2())) {
			basicAddress.setSwitchBj2("500");
			falg = true;
		}
		if(ToolUtil.isEmpty(basicAddress.getLatitude())) {
			basicAddress.setLatitude(basicAddressParam.getLatitude());
			falg = true;
		} else if(!basicAddress.getLatitude().equals(basicAddressParam.getLatitude())) {
			basicAddress.setLatitude(basicAddressParam.getLatitude());
			falg = true;
		}
		if(ToolUtil.isEmpty(basicAddress.getLongitude())) {
			basicAddress.setLongitude(basicAddressParam.getLongitude());
			falg = true;
		} else if (basicAddress.getLongitude().equals(basicAddressParam.getLongitude())) {
			basicAddress.setLongitude(basicAddressParam.getLongitude());
			falg = true;
		}
		if(falg) {
			ToolUtil.copyProperties(basicAddress, basicAddressParam);
			this.basicAddressService.update(basicAddressParam);
		}
		return ResponseData.success();
	}

	/**
	 * 是否取轨迹 接口
	 */
	@RequestMapping("/edittDispatch")
	@ResponseBody
	public ResponseData edittDispatch(TDispatchParam tDispatchParam) {
		TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam,null);
		if(dispatchResult != null) {
			if(dispatchResult.getTstate().equals("已定价")||dispatchResult.getTstate().equals("待发运")||dispatchResult.getTstate().equals("运输中")) {
				tDispatchParam.setId(dispatchResult.getId());
				tDispatchParam.setGuiji("1");
				this.tDispatchService.update(tDispatchParam);
			}
		}
		return ResponseData.success();
	}

	/**
	 * 更新 接口
	 */
	@RequestMapping("/edittDispatch2")
	@ResponseBody
	public ResponseData edittDispatch2(TDispatchParam tDispatchParam) {
		TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam,null);
		if(dispatchResult != null) {
			tDispatchParam.setId(dispatchResult.getId());
			tDispatchParam.setPaiType("yes");
			this.tDispatchService.update(tDispatchParam);
		}
		return ResponseData.success();
	}

	/**
	 * 更新 鹰眼行驶里程、停留次数接口
	 */
	@RequestMapping("/edittDispatchYy")
	@ResponseBody
	public ResponseData edittDispatchYy(TDispatchParam tDispatchParam) {
		TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam,null);
		if(dispatchResult != null) {
			tDispatchParam.setId(dispatchResult.getId());
			this.tDispatchService.update(tDispatchParam);
		}
		return ResponseData.success();
	}

	@Autowired
	private BasicAddressService basicAddressService;

	/**
	 * 围栏报警  自动操作
	 */
	@RequestMapping("/weilan_police")
	@ResponseBody
	public ResponseData weilan_police(TDispatchParam tDispatchParam,String longitude,String latitude) {
		if(ToolUtil.isEmpty(tDispatchParam.getDispatchNumber())|| ToolUtil.isEmpty(longitude) ||ToolUtil.isEmpty(latitude)) {
			return ResponseData.error("缺少参数");
		}
		TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam,null);
		if(dispatchResult.getTstate().equals("已定价")) {
			//校验是否到仓
//			TransportReceiptParam receiptParam = new TransportReceiptParam();
//			receiptParam.setDispatchNumber(tDispatchParam.getDispatchNumber());
//			TransportReceiptResult receiptResult = transportReceiptService.findBySpec(receiptParam);
//			if(receiptResult != null) {
//				if(receiptResult.getSetLocationId() != null){
//					BasicAddress basicAddress =  basicAddressService.getById(receiptResult.getSetLocationId());
//					if(ToolUtil.isNotEmpty(basicAddress.getLongitude())&&ToolUtil.isNotEmpty(basicAddress.getLatitude())) {
//						double a = MapUtils.GetDistance(Double.parseDouble(basicAddress.getLongitude()), Double.parseDouble(basicAddress.getLatitude()), Double.parseDouble(longitude), Double.parseDouble(latitude));
//						double radius = Double.parseDouble(basicAddress.getSwitchBj());
//						if (radius>=a) {
//							ResponseData responseData = new ResponseData();
//							responseData.setCode(1);
//							responseData.setSuccess(true);
//							return responseData;
//						}
//					}
//				}
//			}
		} else if (dispatchResult.getTstate().equals("待发运")) {
			//校验是否离场发运
			TransportReceiptParam receiptParam = new TransportReceiptParam();
			receiptParam.setDispatchNumber(tDispatchParam.getDispatchNumber());
			TransportReceiptResult receiptResult = transportReceiptService.findBySpec(receiptParam);
			if(receiptResult != null) {
				if(receiptResult.getSetLocationId() != null){
					BasicAddress basicAddress =  basicAddressService.getById(receiptResult.getSetLocationId());
					if(ToolUtil.isNotEmpty(basicAddress.getLongitude())&&ToolUtil.isNotEmpty(basicAddress.getLatitude())) {
						double a = MapUtils.GetDistance(Double.parseDouble(basicAddress.getLongitude()), Double.parseDouble(basicAddress.getLatitude()), Double.parseDouble(longitude), Double.parseDouble(latitude));
						double radius = Double.parseDouble(basicAddress.getSwitchBj());
						if (radius<a) {
							ResponseData responseData = new ResponseData();
							responseData.setCode(2);
							responseData.setSuccess(true);
							return responseData;
						}
					}
				}
			}
		} else if (dispatchResult.getTstate().equals("运输中")) {
			//校验是否到达客户地址
//    		TransportReceiptParam transportReceiptParam = new TransportReceiptParam();
//    		transportReceiptParam.setDispatchNumber(tDispatchParam.getDispatchNumber());
//    		List<TransportReceiptResult> list =  transportReceiptService.findListBySpec(transportReceiptParam,null);
//    		for (TransportReceiptResult r : list) {
//    			TransportMsgParam transportMsgParam = new TransportMsgParam();
//    			transportMsgParam.setDispatchNumber(tDispatchParam.getDispatchNumber());
//    			transportMsgParam.setV1(r.getGetLocationid()+"");
//    			transportMsgParam.setStatus("送达");
//    			TransportMsgResult transportMsgResult =  transportMsgService.findBySpec(transportMsgParam);
//    			if(transportMsgResult == null) {
//    				if(r.getGetLocationid() != null){
//    					BasicAddress basicAddress =  basicAddressService.getById(r.getGetLocationid());
//    					if(ToolUtil.isNotEmpty(basicAddress.getLongitude())&&ToolUtil.isNotEmpty(basicAddress.getLatitude())) {
//    						double a = MapUtils.GetDistance(Double.parseDouble(basicAddress.getLongitude()), Double.parseDouble(basicAddress.getLatitude()), Double.parseDouble(longitude), Double.parseDouble(latitude));
//    						double radius = Double.parseDouble(basicAddress.getSwitchBj2());
//    						if (radius>=a) {
//    							ResponseData responseData = new ResponseData();
//    							responseData.setCode(3);
//    							responseData.setSuccess(true);
//    							responseData.setData(r);
//    					        return responseData;
//    						}
//    					}
//    				}
//    			}
//			}

			//记录进入、离开围栏时间
			TransportReceiptParam transportReceiptParam = new TransportReceiptParam();
			transportReceiptParam.setDispatchNumber(tDispatchParam.getDispatchNumber());
			List<TransportReceiptResult> list =  transportReceiptService.findfenceListBySpec(transportReceiptParam);
			for (TransportReceiptResult r : list) {
				if(ToolUtil.isEmpty(r.getEnterFenceTime())) {
					if(r.getGetLocationid() != null){
						BasicAddress basicAddress =  basicAddressService.getById(r.getGetLocationid());
						if(ToolUtil.isNotEmpty(basicAddress.getLongitude())&&ToolUtil.isNotEmpty(basicAddress.getLatitude())) {
							double a = MapUtils.GetDistance(Double.parseDouble(basicAddress.getLongitude()), Double.parseDouble(basicAddress.getLatitude()), Double.parseDouble(longitude), Double.parseDouble(latitude));
							double radius = Double.parseDouble(basicAddress.getSwitchBj2());
							if (radius>=a) {
								TransportReceiptParam update = new TransportReceiptParam();
								update.setId(r.getId());
								update.setEnterFenceTime(DateUtil.getDateS());
								transportReceiptService.update(update);
							}
						}
					}
				} else if (ToolUtil.isEmpty(r.getLeaveFenceTime())) {
					if(r.getGetLocationid() != null){
						BasicAddress basicAddress =  basicAddressService.getById(r.getGetLocationid());
						if(ToolUtil.isNotEmpty(basicAddress.getLongitude())&&ToolUtil.isNotEmpty(basicAddress.getLatitude())) {
							double a = MapUtils.GetDistance(Double.parseDouble(basicAddress.getLongitude()), Double.parseDouble(basicAddress.getLatitude()), Double.parseDouble(longitude), Double.parseDouble(latitude));
							double radius = Double.parseDouble(basicAddress.getSwitchBj());
							if (radius<a) {
								TransportReceiptParam update = new TransportReceiptParam();
								update.setId(r.getId());
								update.setLeaveFenceTime(DateUtil.getDateS());
								transportReceiptService.update(update);
							}
						}
					}
				}
			}
		}
		return ResponseData.success();
	}

	@Autowired
	private TransportMsgService transportMsgService;

	/**
	 * 到仓签到
	 * 查询我的签到
	 */
	@ResponseBody
	@RequestMapping("/finddriverSigninListPageBySpec")
	public LayuiPageInfo finddriverSigninListPageBySpec(TransportMsgParam transportMsgParam) {
		User user = userAop.getUser();
		LayuiPageInfo info = new LayuiPageInfo();

		BasicDriverParam basicDriverParam = new BasicDriverParam();
		basicDriverParam.setUserId(user.getUserId());
		BasicDriverResult basicDriverResult = basicDriverService.findBySpec(basicDriverParam,null);
		BasicPrivatecarResult basicPrivatecarResult = new BasicPrivatecarResult();
		if(basicDriverResult != null) {
			BasicPrivatecarParam BasicPrivatecarParam = new BasicPrivatecarParam();
			BasicPrivatecarParam.setDriverId1(Long.parseLong(basicDriverResult.getId().toString()));
			basicPrivatecarResult = basicPrivatecarService.findBySpec(BasicPrivatecarParam, null,null);
		} else {
			return info;
		}
		if(basicPrivatecarResult == null || ToolUtil.isEmpty(basicPrivatecarResult.getPrivatecarCarnumber())) {
			return info;
		} else {
			transportMsgParam.setV3(basicPrivatecarResult.getId()+"");
			return this.transportMsgService.finddriverSigninListPageBySpec(transportMsgParam,null);
		}
	}

	@Autowired
	private BasicCarrierService basicCarrierService;

	@Autowired
	private BasicDriverService basicDriverService;

	@Autowired
	private UserService userService;

	/**
	 * 到仓签到
	 */
	@RequestMapping("/driverSignin")
	@ResponseBody
	public ResponseData driverSignin(String longitude,String latitude,String currentAddress,Long operateId,String carrierName,String openId) {
		// 经纬度解析地址
		String location = longitude + "," + latitude;
		StringBuilder stringBuilder = new StringBuilder("https://restapi.amap.com/v3/geocode/regeo");
		stringBuilder.append("?key=4bb7b6534a7dd0bee729aa6d42e1f1f2");
		stringBuilder.append("&location=").append(location);
		stringBuilder.append("&radius=").append(200);
		stringBuilder.append("&extensions=").append("all");
		try {
			// 发送GET请求并获取响应
			String url = stringBuilder.toString();
			RestTemplate restTemplate = new RestTemplate();
			String response = restTemplate.getForObject(url, String.class);

			// 将字符串转换为JSONObject
			JSONObject jsonObject = new JSONObject(response);
			// 提取formatted_address
			if(jsonObject.optJSONObject("regeocode") != null) {
				JSONObject regeocode = jsonObject.optJSONObject("regeocode");
				currentAddress = regeocode.optString("formatted_address");
			}

		}catch (Exception e){
			e.printStackTrace();
		}

		//解决参数中的 英文括号
		if (ToolUtil.isNotEmpty(currentAddress)) {
			currentAddress = currentAddress.replace("& #40;", "(");
			currentAddress = currentAddress.replace("& #41;", ")");
		}
		User user = userAop.getUser();
		lock.lock();//获取锁
		try {
			BasicOperate basicOperate = basicOperateService.getById(operateId);

			BasicDriverParam basicDriverParam = new BasicDriverParam();
			basicDriverParam.setUserId(user.getUserId());
			BasicDriverResult basicDriverResult = basicDriverService.findBySpec(basicDriverParam,null);
			BasicPrivatecarResult basicPrivatecarResult = new BasicPrivatecarResult();
			if(basicDriverResult != null) {
				BasicPrivatecarParam BasicPrivatecarParam = new BasicPrivatecarParam();
				BasicPrivatecarParam.setDriverId1(Long.parseLong(basicDriverResult.getId().toString()));
				basicPrivatecarResult = basicPrivatecarService.findBySpec(BasicPrivatecarParam, null,null);
			} else {
				return ResponseData.error("未查询到您的信息，请联系管理员");
			}
			if(basicPrivatecarResult == null || ToolUtil.isEmpty(basicPrivatecarResult.getPrivatecarCarnumber())) {
				return ResponseData.error("未查询到您关联的车辆信息，请联系管理员");
			}

			BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
			basicPutgoodsParam.setUnitCategory("发货");
			basicPutgoodsParam.setDeptId(basicOperate.getDeptId());
			BasicPutgoodsResult sh = basicPutgoodsService.findBySpec(basicPutgoodsParam, Long.parseLong(basicOperate.getId().toString()));//发货
			if(sh == null) {
				return ResponseData.error("未设置签到地，请联系管理员");
			}
			BasicAddressParam basicAddressParam = new BasicAddressParam();
			basicAddressParam.setPutgoodsId(Long.parseLong(sh.getId().toString()));
			BasicAddressResult addressResult = basicAddressService.findBySpec(basicAddressParam);
			if(addressResult == null) {
				return ResponseData.error("未设置签到地址，请联系管理员");
			}

			if(ToolUtil.isNotEmpty(addressResult.getSwitchWl())&&ToolUtil.isNotEmpty(longitude)&&ToolUtil.isNotEmpty(latitude)) {
				if(addressResult.getSwitchWl().equals("1") ) {
					if(ToolUtil.isNotEmpty(addressResult.getLongitude())&&ToolUtil.isNotEmpty(addressResult.getLatitude())) {
						double a = MapUtils.GetDistance(Double.parseDouble(addressResult.getLongitude()), Double.parseDouble(addressResult.getLatitude()), Double.parseDouble(longitude), Double.parseDouble(latitude));
						double radius = Double.parseDouble(addressResult.getSwitchBj());
						if (radius<a) {
							return ResponseData.error("不在签到范围内，无法签到");
						}
					} else {
						return ResponseData.error("签到地址经纬度不存在，请联系管理员");
					}
				}
			}
			TransportMsgParam msgParam = new TransportMsgParam();
			msgParam.setV3(basicPrivatecarResult.getId()+"");
			msgParam.setTimes(DateUtil.getDate());
			msgParam.setStatus("到仓签到");
			TransportMsgResult r = transportMsgService.findZuixinBySpec(msgParam);
			if(r == null) {
				TransportMsgParam transportMsgParam = new TransportMsgParam();
				transportMsgParam.setStatus("到仓签到");
				transportMsgParam.setMsgType("司机");
				transportMsgParam.setContent(currentAddress);
				transportMsgParam.setTimes(DateUtil.getDateS());
				transportMsgParam.setV1(basicPrivatecarResult.getPrivatecarCarnumber());
				transportMsgParam.setV2(user.getPhone());
				transportMsgParam.setV3(basicPrivatecarResult.getId()+"");
				transportMsgParam.setOpenId(openId);
				transportMsgParam.setCreateUsername(user.getName());
				transportMsgParam.setDeptId(basicOperate.getDeptId());
				transportMsgParam.setDeliverId(basicOperate.getDeliverId());
				transportMsgService.add(transportMsgParam);
			} else {
				TransportMsgParam upadatemsgParam = new TransportMsgParam();
				upadatemsgParam.setId(r.getId());
				upadatemsgParam.setContent(currentAddress);
				upadatemsgParam.setTimes(DateUtil.getDateS());
				upadatemsgParam.setOpenId(openId);
				upadatemsgParam.setCreateUsername(user.getName());
				upadatemsgParam.setDeptId(basicOperate.getDeptId());
				upadatemsgParam.setDeliverId(basicOperate.getDeliverId());
				transportMsgService.update(upadatemsgParam);
			}

			if(user.getOperateId() != null) {
				if(!user.getOperateId().equals(operateId)) {
					userService.lambdaUpdate()
					.eq(User::getUserId, user.getUserId())
					.set(User::getOperateId, operateId)
					.set(User::getDeptId, basicOperate.getDeptId())
					.update();

					BasicDriverParam BasicDriverParamupdate = new BasicDriverParam();
					BasicDriverParamupdate.setId(basicDriverResult.getId());
					BasicDriverParamupdate.setDeptId(basicOperate.getDeptId());
					BasicDriverParamupdate.setDriverOperateId(basicOperate.getId());
					BasicDriverParamupdate.setDriverOperateName(basicOperate.getOperateName());
					basicDriverService.update(BasicDriverParamupdate);

					BasicPrivatecarParam BasicPrivatecarParamupdate = new BasicPrivatecarParam();
					BasicPrivatecarParamupdate.setId(basicPrivatecarResult.getId());
					BasicPrivatecarParamupdate.setDeptId(basicOperate.getDeptId());
					BasicPrivatecarParamupdate.setOperateId(operateId);
					BasicPrivatecarParamupdate.setOperateName(basicOperate.getOperateName());
					basicPrivatecarService.update(BasicPrivatecarParamupdate);
				}
			}

			BasicCarrierParam check = new BasicCarrierParam();
			check.setCarrierName(carrierName);
			check.setV1("1");
			BasicCarrierResult Carrierr = basicCarrierService.findBySpec(check,null);
			if(Carrierr != null) {
				BasicPrivatecarParam updatecar = new BasicPrivatecarParam();
				updatecar.setId(basicPrivatecarResult.getId());
				updatecar.setPrivatecarFleetId(Carrierr.getId());
				updatecar.setPrivatecarFleetName(Carrierr.getCarrierName());
				basicPrivatecarService.update(updatecar);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
		return ResponseData.success();
	}

	@Autowired
	private TransportStevedoreSigninService transportStevedoreSigninService;

	@Autowired
	private BasicOperateService basicOperateService;

	/**
	 * 装卸签到
	 */
	@RequestMapping("/signin")
	@ResponseBody
	public ResponseData signin(TransportStevedoreSigninParam transportStevedoreSigninParam,String longitude,String latitude,String currentAddress) {
		if(ToolUtil.isEmpty(transportStevedoreSigninParam.getAuditTime()) ||ToolUtil.isEmpty(transportStevedoreSigninParam.getTel())) {
			return ResponseData.error("请输入姓名、电话");
		}
		BasicOperate operate = basicOperateService.getById(transportStevedoreSigninParam.getOperateId());
		transportStevedoreSigninParam.setSigninTimes(DateUtil.getDateS());
		transportStevedoreSigninParam.setV1(currentAddress);
		transportStevedoreSigninParam.setDeptId(operate.getDeptId());
		transportStevedoreSigninParam.setDeliverId(operate.getDeliverId());

		BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
		basicPutgoodsParam.setUnitCategory("发货");
		basicPutgoodsParam.setDeptId(operate.getDeptId());
		BasicPutgoodsResult sh = basicPutgoodsService.findBySpec(basicPutgoodsParam, transportStevedoreSigninParam.getOperateId());//发货
		if(sh == null) {
			return ResponseData.error("未设置签到地，请联系管理员");
		}
		BasicAddressParam basicAddressParam = new BasicAddressParam();
		basicAddressParam.setPutgoodsId(Long.parseLong(sh.getId().toString()));
		BasicAddressResult addressResult = basicAddressService.findBySpec(basicAddressParam);
		if(addressResult == null) {
			return ResponseData.error("未设置签到地址，请联系管理员");
		}

		if(ToolUtil.isNotEmpty(addressResult.getSwitchWl())) {
			if(addressResult.getSwitchWl().equals("1")&&ToolUtil.isNotEmpty(longitude)&&ToolUtil.isNotEmpty(latitude)) {
				if(ToolUtil.isNotEmpty(addressResult.getLongitude())&&ToolUtil.isNotEmpty(addressResult.getLatitude())) {
					double a = MapUtils.GetDistance(Double.parseDouble(addressResult.getLongitude()), Double.parseDouble(addressResult.getLatitude()), Double.parseDouble(longitude), Double.parseDouble(latitude));
					double radius = Double.parseDouble(addressResult.getSwitchBj());
					if (radius<a) {
						return ResponseData.error("不在签到范围内，无法签到");
					}
				} else {
					return ResponseData.error("签到地址经纬度不存在，请联系管理员");
				}
			}
		}
		TransportStevedoreSigninParam check = new TransportStevedoreSigninParam();
		check.setAuditTime(transportStevedoreSigninParam.getAuditTime());
		check.setTel(transportStevedoreSigninParam.getTel());
		check.setDeptId(Long.parseLong(operate.getId().toString()));
		TransportStevedoreSigninResult ch = transportStevedoreSigninService.findBySpec(check,transportStevedoreSigninParam.getOperateId());//校验签到过没有
		if(ch != null) {
			transportStevedoreSigninParam.setAuditBy(ch.getAuditBy());
			transportStevedoreSigninService.add(transportStevedoreSigninParam);
			return ResponseData.success(ch.getAuditBy());
		} else {
			TransportStevedoreSigninParam last = new TransportStevedoreSigninParam();
			last.setDeptId(Long.parseLong(operate.getId().toString()));
			TransportStevedoreSigninResult lastres = transportStevedoreSigninService.findlastBySpec(last,transportStevedoreSigninParam.getOperateId());//查询最大工号
			if(lastres != null) {
				int auditBy = Integer.parseInt(lastres.getAuditBy().toString());
				transportStevedoreSigninParam.setAuditBy((auditBy+1)+"");
				transportStevedoreSigninService.add(transportStevedoreSigninParam);
				return ResponseData.success(auditBy+1);
			} else {
				transportStevedoreSigninParam.setAuditBy("1");
				transportStevedoreSigninService.add(transportStevedoreSigninParam);
				return ResponseData.success(1);
			}
		}
	}

	/**
	 * 装卸签退
	 */
	@RequestMapping("/signout")
	@ResponseBody
	public ResponseData signout(TransportStevedoreSigninParam transportStevedoreSigninParam,String longitude,String latitude,String currentAddress) {
		if(ToolUtil.isEmpty(transportStevedoreSigninParam.getAuditTime()) ||ToolUtil.isEmpty(transportStevedoreSigninParam.getTel())) {
			return ResponseData.error("请输入姓名、电话");
		}
		BasicOperate operate = basicOperateService.getById(transportStevedoreSigninParam.getOperateId());
		TransportStevedoreSigninParam update = new TransportStevedoreSigninParam();
		update.setSignoutTimes(DateUtil.getDateS());
		update.setV2(currentAddress);

		BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
		basicPutgoodsParam.setUnitCategory("发货");
		basicPutgoodsParam.setDeptId(operate.getDeptId());
		BasicPutgoodsResult sh = basicPutgoodsService.findBySpec(basicPutgoodsParam, transportStevedoreSigninParam.getOperateId());//发货
		if(sh == null) {
			return ResponseData.error("未设置签到地，请联系管理员");
		}
		BasicAddressParam basicAddressParam = new BasicAddressParam();
		basicAddressParam.setPutgoodsId(Long.parseLong(sh.getId().toString()));
		BasicAddressResult addressResult = basicAddressService.findBySpec(basicAddressParam);
		if(addressResult == null) {
			return ResponseData.error("未设置签到地址，请联系管理员");
		}

		if(ToolUtil.isNotEmpty(addressResult.getSwitchWl())) {
			if(addressResult.getSwitchWl().equals("1")&&ToolUtil.isNotEmpty(longitude)&&ToolUtil.isNotEmpty(latitude)) {
				if(ToolUtil.isNotEmpty(addressResult.getLongitude())&&ToolUtil.isNotEmpty(addressResult.getLatitude())) {
					double a = MapUtils.GetDistance(Double.parseDouble(addressResult.getLongitude()), Double.parseDouble(addressResult.getLatitude()), Double.parseDouble(longitude), Double.parseDouble(latitude));
					double radius = Double.parseDouble(addressResult.getSwitchBj());
					if (radius<a) {
						return ResponseData.error("不在签到范围内，无法签到");
					}
				} else {
					return ResponseData.error("签到地址经纬度不存在，请联系管理员");
				}
			}
		}
		TransportStevedoreSigninParam check = new TransportStevedoreSigninParam();
		check.setAuditTime(transportStevedoreSigninParam.getAuditTime());
		check.setTel(transportStevedoreSigninParam.getTel());
		check.setDeptId(Long.parseLong(operate.getId().toString()));
		TransportStevedoreSigninResult ch = transportStevedoreSigninService.findBySpec(check,transportStevedoreSigninParam.getOperateId());//校验签到过没有
		if(ch != null) {
			if(ToolUtil.isNotEmpty(ch.getSignoutTimes())) {
				return ResponseData.error("请先签到，再签退");
			} else {
				update.setId(ch.getId());
				transportStevedoreSigninService.update(update);
				return ResponseData.success();
			}
		} else {
			return ResponseData.error("请先签到，再签退");
		}
	}

	@Autowired
	private OrderOutpreparePlatooncarService orderOutpreparePlatooncarService;

	/**
	 * 查询我的派车计划
	 */
	@ResponseBody
	@RequestMapping("/findorderOutpreparePlatooncar")
	public ResponseData findorderOutpreparePlatooncar(OrderOutpreparePlatooncarParam orderOutpreparePlatooncarParam) {
		User user = userAop.getUser();
		if(ToolUtil.isNotEmpty(user.getPhone())) {
			orderOutpreparePlatooncarParam.setSijidianhua2(user.getPhone());
		}
		orderOutpreparePlatooncarParam.setSijidianhua(user.getAccount());
//		orderOutpreparePlatooncarParam.setSijidianhua("13255443380");

		List<OrderOutpreparePlatooncarResult> list = orderOutpreparePlatooncarService.findListBySpec(orderOutpreparePlatooncarParam,user.getOperateId());
		return ResponseData.success(list);
	}

	/**
	 * 确认排车计划
	 */
	@ResponseBody
	@RequestMapping("/queren")
	public ResponseData queren() {
//		OrderOutpreparePlatooncarParam parm = new OrderOutpreparePlatooncarParam();
//		parm.setId(id);
//		parm.setStat("已确认");
		User user = userAop.getUser();
		orderOutpreparePlatooncarService.updateByDianHua("已确认",user.getAccount());
		return ResponseData.success();
	}

	/**
	 * 确认排车计划
	 */
	@ResponseBody
	@RequestMapping("/quxiao")
	public ResponseData quxiao() {
		User user = userAop.getUser();
		orderOutpreparePlatooncarService.updateByDianHua("已拒绝",user.getAccount());
		return ResponseData.success();
	}

	/**
	 * 查询是否有待定价的运单
	 */
	@ResponseBody
	@RequestMapping("/findshifouyipeizhiByspec")
	public ResponseData findshifouyipeizhiByspec(TDispatchParam tDispatchParam) {
		User user = userAop.getUser();
		Long operateId = tDispatchParam.getOperateId();
		BasicDriverParam basicDriverParam = new BasicDriverParam();
		basicDriverParam.setUserId(user.getUserId());
		BasicDriverResult basicDriverResult = basicDriverService.findBySpec(basicDriverParam,null);
		BasicPrivatecarResult basicPrivatecarResult = new BasicPrivatecarResult();
		if(basicDriverResult != null) {
			BasicPrivatecarParam BasicPrivatecarParam = new BasicPrivatecarParam();
			BasicPrivatecarParam.setDriverId1(Long.parseLong(basicDriverResult.getId().toString()));
			basicPrivatecarResult = basicPrivatecarService.findBySpec(BasicPrivatecarParam, null,null);
		}
		List<TDispatchResult> res = new ArrayList<TDispatchResult>();
		if(basicPrivatecarResult != null && ToolUtil.isNotEmpty(basicPrivatecarResult.getPrivatecarCarnumber())) {
			tDispatchParam.setCarId(Long.parseLong(basicPrivatecarResult.getId().toString()));
			if(operateId != null) {
				BasicOperate basicOperate = basicOperateService.getById(operateId);
				tDispatchParam.setDeptId(basicOperate.getDeptId());
			} else {
				operateId = user.getOperateId();
				tDispatchParam.setDeptId(user.getDeptId());
			}
			res = tDispatchService.findshifouyipeizhiByspec(tDispatchParam,operateId);
		}
		return ResponseData.success(res);
	}

	/**
	 * 通过微信用户登录凭证 换取openid
	 */
	@ResponseBody
	@RequestMapping("/getopenId")
	public ResponseData getopenId(String code) {
		if(ToolUtil.isNotEmpty(code)) {
	        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxbd4376e47f683cc8&secret=f738b92ee10816f451e386466ffdbc13&js_code="+code+"&grant_type=authorization_code";
			String post = HttpRequest.post(url)
						.execute().body();
//			System.out.println("================post："+post+"========================");
	    	JSONObject jsonObject = new JSONObject(post);
			return ResponseData.success(jsonObject.get("openid").toString());
		}
		return ResponseData.success();
	}

	/**
	 * 打印零售发货单
	 * 查询订单门店
	 */
	@ResponseBody
	@RequestMapping("/getAutoPrint")
	public ResponseData getAutoPrint(String dispatchNumber) {

		TDispatch tDispatch = this.tDispatchService.lambdaQuery().eq(TDispatch::getDispatchNumber, dispatchNumber).one();
		if(tDispatch == null){
			return ResponseData.error("货运订单不存在！");
		}
		List<PrintSumVo> printSumList = new ArrayList<>();
		//是否存在新零帮发货订单号 若存在则通过接口
		if(ToolUtil.isNotEmpty(tDispatch.getXlbDepartOrderId())){
			//根据货运订单号 获取托运单号
			TransportDispatch transportDispatch = this.transportDispatchService.lambdaQuery().eq(TransportDispatch::getDispatchNumber, dispatchNumber).one();
			if(transportDispatch == null){
				return ResponseData.error("托运订单不存在！");
			}
			//根据托运订单获取客户编号
			OrderTransport orderTransport = this.orderTransportService.lambdaQuery().eq(OrderTransport::getTransportNumber, transportDispatch.getTransportNumber()).one();
			if(orderTransport == null){
				return ResponseData.error("托运订单不存在！");
			}
			if(ToolUtil.isEmpty(orderTransport.getCustomerId())){
				return ResponseData.error("客户编号不存在！");
			}
			//根据客户编号，获取 gsnumber
			BasicCustomer basicCustomer = this.basicCustomerService.getById(orderTransport.getCustomerId());
			if(basicCustomer == null){
				return ResponseData.error("客户不存在！");
			}
			if(ToolUtil.isEmpty(basicCustomer.getGsnumber())){
				return ResponseData.error("客户未配置【公司号】，无法获取新零帮发车信息！");
			}
			BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
			oauth2tokenParam.setDeliverId(basicCustomer.getDeliverId());
			oauth2tokenParam.setGsnumber(basicCustomer.getGsnumber());
			BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
			if(oauth2tokenResult == null || ToolUtil.isEmpty(oauth2tokenResult.getOauth2TokenXlb())){
				return ResponseData.error("未配置该客户的token信息，无法获取新零帮发车信息！");
			}
			String url = hxlApiUrl + "/hxl.open.wms.departurecenter.batch.find";
			JSONObject json = new JSONObject();
			json.put("company_id", oauth2tokenResult.getGsnumber());
			json.put("fids", ListUtil.of(tDispatch.getXlbDepartOrderId()));
			String post = HttpRequest.post(url)
					.header("Authorization","bearer "+oauth2tokenResult.getOauth2TokenXlb()).body(json.toString()).execute().body();
			JSONObject jsonObject = new JSONObject(post);
			if(jsonObject.get("code").toString().equals("0")) {
				List<StorageTaskXlb> xlbs = new ArrayList<StorageTaskXlb>();
				JSONArray jsonArray = new JSONArray(jsonObject.get("data").toString());
				for (Object object : jsonArray) {
					JSONObject jsonObject2 = new JSONObject(object.toString());
					String fid = jsonObject2.get("fid").toString().replaceAll("\t\r\n", "");
				}
			}
		}else{
			//获取总数
			List<OrderTransportResult> orderTransportList = this.orderTransportService.findAutoPrintSum(OrderTransportParam.builder()
					.dispatchNumber(dispatchNumber)
					.build());
			Map<String,OrderTransportResult> orderTransportMap = new HashMap<>();
			for(OrderTransportResult obj : orderTransportList){
				orderTransportMap.put(obj.getGetUnitId().toString(),obj);
			}

			//获取单品数量
			List<TransportDispatchResult> transportDispatchList = transportDispatchService.findAutoPrintByDispatchNumber(dispatchNumber);
			Map<String,List<TransportDispatchResult>> transportDispatchMap = new HashMap<>();
			List<TransportDispatchResult> TransportDispatchResultList = null;
			String _getUnitId = "";
			for(TransportDispatchResult obj : transportDispatchList){
				String key = obj.getGetUnitId().toString();
				if(!_getUnitId.equals(key)){
					_getUnitId = key;
					TransportDispatchResultList = new ArrayList<>();
					TransportDispatchResultList.add(obj);
					transportDispatchMap.put(key,TransportDispatchResultList);
				}else{
					TransportDispatchResultList.add(obj);
				}
			}
			//组装打印信息
			PrintSumVo _printSumVo = null;
			for(String key : orderTransportMap.keySet()){
				int row = 1;
				_printSumVo = new PrintSumVo();
				_printSumVo.setGetUnitid(orderTransportMap.get(key).getGetUnitId().toString());
				_printSumVo.setGetUnit(orderTransportMap.get(key).getGetUnit());
				_printSumVo.setGetLocation(orderTransportMap.get(key).getGetLocation());
				_printSumVo.setSetMentiontime(orderTransportMap.get(key).getSetMentiontime());
				_printSumVo.setSetUnit(orderTransportMap.get(key).getSetUnit());
				_printSumVo.setGetTel(orderTransportMap.get(key).getGetTel());
				_printSumVo.setClSum(orderTransportMap.get(key).getClSum());
				_printSumVo.setZxSum(orderTransportMap.get(key).getZxSum());
				BigDecimal clSum = new BigDecimal(0);
				if(ToolUtil.isNotEmpty(_printSumVo.getClSum())){
					clSum = new BigDecimal(_printSumVo.getClSum());
				}
				BigDecimal zxSum = new BigDecimal(0);
				if(ToolUtil.isNotEmpty(_printSumVo.getZxSum())){
					zxSum = new BigDecimal(_printSumVo.getZxSum());
				}
				BigDecimal sum = clSum.add(zxSum);
				_printSumVo.setAllSum(sum.toString());

				String _goodsBigtype = "";
				if(transportDispatchMap.get(key) != null && transportDispatchMap.get(key).size() > 0){
					for(TransportDispatchResult obj : transportDispatchMap.get(key)){
						if(ToolUtil.isNotEmpty(obj.getGoodsBigtype()) && !_goodsBigtype.equals(obj.getGoodsBigtype())){
							_goodsBigtype = obj.getGoodsBigtype();
							_printSumVo.getPrintGoodList().add(PrintGoodVo.builder()
									.seq(row)
									.goodsNumber(_goodsBigtype)
									.goodsName("")
									.goodsSpecs("")
									.goodsUnit("")
									.tooDeployNum("")
									.detailedDate("")
									.goodsWarranty("")
									.build());
							row++;
						}
						_printSumVo.getPrintGoodList().add(PrintGoodVo.builder()
								.seq(row)
								.goodsNumber(obj.getGoodsNumber())
								.goodsName(obj.getGoodsName())
								.goodsSpecs(obj.getGoodsSpecs())
								.goodsUnit(obj.getGoodsUnit())
								.tooDeployNum(obj.getTooDeployNum())
								.detailedDate(obj.getDetailedDate())
								.goodsWarranty(obj.getGoodsWarranty())
								.build());
						row++;
					}

					_printSumVo.getPrintGoodList().add(PrintGoodVo.builder()
							.seq(null)
							.goodsNumber("")
							.goodsName("")
							.goodsSpecs("")
							.goodsUnit("数量合计：")
							.tooDeployNum(sum.toString())
							.detailedDate("")
							.goodsWarranty("")
							.build());
				}
				printSumList.add(_printSumVo);

			}
		}

		return ResponseData.success(printSumList);
	}

	@RequestMapping("/dianziqianyue")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class, timeout = 180)
	public ResponseData dianziqianyue(TDispatchParam tDispatchParam) {
		User user = userAop.getUser();
		synchronized (tDispatchParam.getDispatchNumber()) {
			TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam, null);
//            if(ToolUtil.isNotEmpty(dispatchResult.getSginKey())){
//                return ResponseData.error("已完成信息同步，请在相应司机端进行签署");
//            }
			if (ToolUtil.isEmpty(dispatchResult.getXlbDepartOrderId())) {
				return ResponseData.error("未获取到新零帮发车单号，无法电子签约");
			}
			BasicCustomerParam basicCustomerParam = new BasicCustomerParam();
			basicCustomerParam.setCustomerOperateId(Integer.parseInt(dispatchResult.getOperateId().toString()));
			BasicCustomerResult cr = basicCustomerService.findBySpec(basicCustomerParam, null);
			if (cr == null) {
				return ResponseData.error("客户信息不存在，无法电子签约");
			}
			if (ToolUtil.isEmpty(cr.getStoreIdXlb())) {
				return ResponseData.error("发货门店id未配置，无法电子签约");
			}
			if (ToolUtil.isEmpty(cr.getGsnumber())) {
				return ResponseData.error("新零帮公司号未配置，无法电子签约");
			}
			if (!"是".equals(cr.getIsEtcSign())) {
				return ResponseData.error("客户未配置【电子签收】，无法电子签约");
			}
			Map<String, String> map = new HashMap<>();
			map.put("plate_number", dispatchResult.getCarnumber());
			map.put("driver_name", dispatchResult.getSiji());
			map.put("driver_tel", dispatchResult.getSijidianhua());
			BasicPrivatecar basicPrivatecar = basicPrivatecarService.getById(dispatchResult.getCarId());
			if (basicPrivatecar == null) {
				return ResponseData.error("未获取到车辆信息，无法电子签约");
			}

			// 车辆绑定司机
			if(ToolUtil.isEmpty(basicPrivatecar.getDriver1())){
				return ResponseData.error("车辆请先绑定司机！");
			}

			// 校验司机姓名，不能包含数字
			if (basicPrivatecar.getDriver1().matches(".*\\d+.*")) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				return ResponseData.error("电子签收不允许车辆绑定司机[" + basicPrivatecar.getDriver1() + "]名称包含数字！");
			}

			// 判断手机号是否合法
			String pattern = "^1[3-9]\\d{9}$";
			Pattern r = Pattern.compile(pattern);
			Matcher m = r.matcher(basicPrivatecar.getTel1());
			if (!m.matches()) {
				return ResponseData.error("["+basicPrivatecar.getTel1()+"],司机手机号码不正确，请更正后重试！");
			}

			BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
			oauth2tokenParam.setDeliverId(user.getDeliverId());
			oauth2tokenParam.setGsnumber(cr.getGsnumber());
			BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
			if (oauth2tokenResult == null) {
				return ResponseData.error("未获取到客户对接信息，无法电子签约");
			}

			//同步车辆信息
			String etcCarUrl = this.hxlApiUrl + "/hxl.open.tms.driver.sync";
			JSONObject jsonEtcCarSync = new JSONObject();
			List<Map<String, Object>> etcCarList = new ArrayList<>();
			Map<String, Object> etcCarMap = new HashMap<>();
//			Map<String, Object> etcCarTypeMap = new HashMap<>();
//			etcCarTypeMap.put("source_id", DigestUtils.md5Hex(basicPrivatecar.getPrivatecarType()));
//			etcCarTypeMap.put("name", basicPrivatecar.getPrivatecarType());
//			etcCarMap.put("car_type", etcCarTypeMap);
			List<DictResult> dictResult = dictService.findByDicttypeCode2("XLB_CAR_TYPE_ID");
			if(ToolUtil.isNotEmpty(dictResult)){
				etcCarMap.put("car_type_id", dictResult.get(0).getCode());//暂定车辆类型
			}else if("1000".equals(cr.getGsnumber())){
				etcCarMap.put("car_type_id", "100000000441");//暂定车辆类型
			}else{
				etcCarMap.put("car_type_id", "6666600000001");//暂定车辆类型
			}

			etcCarMap.put("plate_number", basicPrivatecar.getPrivatecarCarnumber());
//            etcCarMap.put("source_id", basicPrivatecar.getId());
			Long carId = IdUtil.createSnowflake(1,1).nextId();
			etcCarMap.put("source_id", carId);//你车辆的source_id. 你每次重新生成吧 20241229
			etcCarList.add(etcCarMap);
			jsonEtcCarSync.put("cars", etcCarList);
			jsonEtcCarSync.put("real_name", basicPrivatecar.getDriver1());
			jsonEtcCarSync.put("source_id", basicPrivatecar.getDriverId1());//把发车单号，当作唯一值
			jsonEtcCarSync.put("source_system", "XIANFEI");
			jsonEtcCarSync.put("tel", basicPrivatecar.getTel1());
			jsonEtcCarSync.put("verified", true);
//            jsonEtcCarSync.put("carrier_id", "100100000046");
			if("1000".equals(cr.getGsnumber())){
				jsonEtcCarSync.put("carrier_id", "100000000383");//暂定车辆类型
			}else{
				jsonEtcCarSync.put("carrier_id", "100100000046");//暂定车辆类型
			}
			String etcCarSyncRes = HttpRequest.post(etcCarUrl)
					.timeout(60000)
					.contentType("application/json;charset=UTF-8")
					.header("Accept", "application/json")
					.header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(jsonEtcCarSync.toString()).execute().body();
			JSONObject etcCarSyncObject = new JSONObject(etcCarSyncRes);
			if (!"0".equals(etcCarSyncObject.get("code").toString())) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				String msg = etcCarSyncObject.get("msg").toString();
				return ResponseData.error("电子签[同步车辆信息]错误：" + msg);
			}
			if(ToolUtil.isEmpty(dispatchResult.getSginKey())){
				//同步运单信息
				String etcSignUrl = this.hxlApiUrl + "/hxl.open.tms.transportOrder.sync";
				JSONObject jsonEtc = new JSONObject();
				jsonEtc.put("depart_order_fid", dispatchResult.getXlbDepartOrderId()); //发车单
				jsonEtc.put("driver_id", basicPrivatecar.getDriverId1()); //司机id 为来源方系统ID
				jsonEtc.put("source_id", dispatchResult.getId()); //来源系统方的ID
				jsonEtc.put("source_system", "XIANFEI"); //来源系统 先飞为 XIANFEI,可用值:LOCAL,XIANFEI
				jsonEtc.put("store_id", cr.getStoreIdXlb()); //门店id
				jsonEtc.put("store_name", cr.getCustomerName()); //门店名称
				jsonEtc.put("state", "TRANSITING"); //运输中
				jsonEtc.put("electric_sign", true); //是否电子签
				jsonEtc.put("storehouse_id", cr.getXlbStorehouseId());
				jsonEtc.put("actual_kilometers",dispatchResult.getMileageTraveled());//实际里程
				jsonEtc.put("car_id",carId);//车辆id
				jsonEtc.put("carrier_id","100100000046");//承运商id
				jsonEtc.put("carrier_name",dispatchResult.getCarrierName());//承运商名称
				jsonEtc.put("departed_time",dispatchResult.getFayunTimes());//发车时间
				jsonEtc.put("driver_name",dispatchResult.getSiji());//司机名称
				jsonEtc.put("driver_phone",dispatchResult.getSijidianhua());//司机电话
				jsonEtc.put("dispatcher",dispatchResult.getDianduyuan());//调度人
				jsonEtc.put("load_rate", dispatchResult.getFulllv());//满载率
				jsonEtc.put("memo",dispatchResult.getNotes());//备注
				jsonEtc.put("plate_number",dispatchResult.getCarnumber());//车牌号
				jsonEtc.put("volume",dispatchResult.getToovolume());//装载体积(m³)
				//
				List<Map<String, String>> tranTsportMaps = new ArrayList<>();
				Map<String, String> mapParmTranTsport;
				BigDecimal pieceNumberSum = BigDecimal.ZERO;
				BigDecimal tooDeployNumSum = BigDecimal.ZERO;
				List<OrderTransportResult> unitList = orderTransportService.getUnitList(dispatchResult.getDispatchNumber());
				for (OrderTransportResult obj : unitList) {
					BigDecimal _numSum = BigDecimal.ZERO;
					mapParmTranTsport = new HashMap<>();
					mapParmTranTsport.put("client_id", obj.getXlbClientId());
					mapParmTranTsport.put("client_name", obj.getGetUnit());
					tranTsportMaps.add(mapParmTranTsport);
					if(ToolUtil.isNotEmpty(obj.getPieceNumber())){
						pieceNumberSum = pieceNumberSum.add(new BigDecimal(obj.getPieceNumber()));
						_numSum = _numSum.add(new BigDecimal(obj.getPieceNumber()));
					}
					if(ToolUtil.isNotEmpty(obj.getTooDeployNum())){
						tooDeployNumSum = tooDeployNumSum.add(new BigDecimal(obj.getTooDeployNum()));
						_numSum = _numSum.add(new BigDecimal(obj.getTooDeployNum()));
					}
					mapParmTranTsport.put("check_quantity", _numSum.toString());
					mapParmTranTsport.put("pick_quantity", _numSum.toString());
					mapParmTranTsport.put("pick_state", "FINISH");
					mapParmTranTsport.put("check_state", "FINISH");

					jsonEtc.put("storehouse_name", obj.getSetUnit());
				}
				BigDecimal numSum = pieceNumberSum.add(tooDeployNumSum);
				jsonEtc.put("whole_quantity",tooDeployNumSum);//整件数量
				jsonEtc.put("open_stock_quantity",pieceNumberSum);//拆零数量
				jsonEtc.put("order_count",numSum);//订单数
				jsonEtc.put("pick_item_count",numSum);//拣货数量
				jsonEtc.put("pick_quantity",numSum);//拣货数量
				jsonEtc.put("pick_state","FINISH");//拣货数量
				jsonEtc.put("quantity",numSum);//拣货数量
				jsonEtc.put("total_kilometers",dispatchResult.getMileageTraveled());//总公里数
				jsonEtc.put("weight",numSum);//拣货数量
				jsonEtc.put("transport_time",dispatchResult.getFayunTimes());//配送日期
				jsonEtc.put("departed_time",dispatchResult.getFayunTimes());//发车时间
				jsonEtc.put("dispatch_time",dispatchResult.getFayunTimes());// 调度时间
				jsonEtc.put("dispatcher",dispatchResult.getDianduyuan());//调度人

				jsonEtc.put("transport_clients", tranTsportMaps); //门店名称
				String etcSignRes = HttpRequest.post(etcSignUrl)
						.timeout(60000)
						.contentType("application/json;charset=UTF-8")
						.header("Accept", "application/json")
						.header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(jsonEtc.toString()).execute().body();
				JSONObject etcSignObject = new JSONObject(etcSignRes);
				if (!"0".equals(etcSignObject.get("code").toString())) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
					String msg = etcSignObject.get("msg").toString();
					return ResponseData.error("电子签[同步运单信息]错误：" + msg);
				}else{
					if(ToolUtil.isNotEmpty(etcSignObject.get("data"))){
						tDispatchService.lambdaUpdate()
								.eq(TDispatch::getId,dispatchResult.getId())
								.set(TDispatch::getSginKey,etcSignObject.get("data").toString())
								.update();
					}
				}
			}
			//重新修改 运单和司机的绑定关系
			String tranDriveUpdateUrl = this.hxlApiUrl + "/hxl.open.tms.transportOrder.update.driver";
			JSONObject tranDriveUpdateObj = new JSONObject();
			tranDriveUpdateObj.put("source_driver_id", basicPrivatecar.getDriverId1());
			tranDriveUpdateObj.put("source_id", dispatchResult.getId());
			tranDriveUpdateObj.put("source_system", "XIANFEI"); //来源系统 先飞为 XIANFEI,可用值:LOCAL,XIANFEI
			String tranDriveUpdateRes = HttpRequest.post(tranDriveUpdateUrl)
					.timeout(60000)
					.contentType("application/json;charset=UTF-8")
					.header("Accept", "application/json")
					.header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(tranDriveUpdateObj.toString()).execute().body();
			JSONObject tranDriveUpdateObject = new JSONObject(tranDriveUpdateRes);
			if (!"0".equals(tranDriveUpdateObject.get("code").toString())) {
				String msg = tranDriveUpdateObject.get("msg").toString();
				return ResponseData.error("电子签[更改运单司机信息]错误：" + msg);
			}

			//生成电子签约
			String etcSignGenUrl = this.hxlApiUrl + "/hxl.open.tms.signature.generate";
			JSONObject jsonEtcGen = new JSONObject();
			jsonEtcGen.put("depart_fid", dispatchResult.getXlbDepartOrderId());
			jsonEtcGen.put("store_id", cr.getStoreIdXlb());
			String etcSignGenRes = HttpRequest.post(etcSignGenUrl)
					.timeout(60000)
					.contentType("application/json;charset=UTF-8")
					.header("Accept", "application/json")
					.header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(jsonEtcGen.toString()).execute().body();
			JSONObject etcSignGenObject = new JSONObject(etcSignGenRes);
			if (!"0".equals(etcSignGenObject.get("code").toString())) {
//				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				String msg = etcSignGenObject.get("msg").toString();
				return ResponseData.error("电子签[生成电子签约]错误：" + msg);
			}
		}
		return ResponseData.success();
	}
	@RequestMapping("/qianshouerweima")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class, timeout = 180)
	public ResponseData qianshouerweima(TDispatchParam tDispatchParam) {

		synchronized (tDispatchParam.getDispatchNumber()) {
			TDispatchResult dispatchResult = tDispatchService.findBySpec(tDispatchParam, null);
			if (ToolUtil.isEmpty(dispatchResult.getXlbDepartOrderId())) {
				return ResponseData.error("未获取到新零帮发车单号，无法电子签约");
			}
			BasicCustomerParam basicCustomerParam = new BasicCustomerParam();
			basicCustomerParam.setCustomerOperateId(Integer.parseInt(dispatchResult.getOperateId().toString()));
			BasicCustomerResult cr = basicCustomerService.findBySpec(basicCustomerParam, null);
			if (cr == null) {
				return ResponseData.error("客户信息不存在，无法电子签约");
			}
			if (ToolUtil.isEmpty(cr.getStoreIdXlb())) {
				return ResponseData.error("发货门店id未配置，无法电子签约");
			}
			if (ToolUtil.isEmpty(cr.getGsnumber())) {
				return ResponseData.error("新零帮公司号未配置，无法电子签约");
			}
			if(ToolUtil.isEmpty(dispatchResult.getSginKey())){
				return ResponseData.error("未同步电子签信息，无法获取签收二维码");
			}
			BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
			oauth2tokenParam.setGsnumber(cr.getGsnumber());
			BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
			if (oauth2tokenResult == null) {
				return ResponseData.error("未获取到客户对接信息，无法电子签约");
			}

			//二维码
//			if(!"".equals(dispatchResult.getSginUrl())){
//				return ResponseData.success("www.baidu.com");
//			}
			String etcSignGenUrl = this.hxlApiUrl + "/hxl.open.tms.sign.url.person.find";
			JSONObject jsonEtcGen = new JSONObject();
			jsonEtcGen.put("fids", ListUtil.of(dispatchResult.getSginKey()));
			jsonEtcGen.put("client_id", tDispatchParam.getXlbClientId());
			jsonEtcGen.put("end_point", "WEIXINAPP");
			jsonEtcGen.put("recipient", "RECIPIENT");
			String etcSignGenRes = HttpRequest.post(etcSignGenUrl)
					.timeout(60000)
					.contentType("application/json;charset=UTF-8")
					.header("Accept", "application/json")
					.header("Authorization", "bearer " + oauth2tokenResult.getOauth2TokenXlb()).body(jsonEtcGen.toString()).execute().body();
			JSONObject etcSignGenObject = new JSONObject(etcSignGenRes);
			if ("0".equals(etcSignGenObject.get("code").toString())) {
				JSONObject data = new JSONObject(etcSignGenObject.get("data").toString());
				JSONArray jsonArray = new JSONArray(data.get("sign_urls").toString());
				for (Object object : jsonArray) {
					JSONObject jsonObject2 = new JSONObject(object.toString());
					if(jsonObject2.get("sign_url") != null && !"".equals(jsonObject2.get("sign_url").toString())){
						return ResponseData.success(jsonObject2.get("sign_url").toString());
					}
				}
			}else{
				return ResponseData.error(etcSignGenObject.get("msg").toString());
			}
		}
		return ResponseData.success();
	}


}
